<?php

class ControllerCatalogMVDProduct extends Controller {
	private $error = array();

	public function index() {
		$this->load->language('catalog/mvd_product');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('catalog/mvd_product');

		$this->getList();
	}

	public function add() {
		$this->load->language('catalog/mvd_product');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('catalog/mvd_product');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {

			$pid = $this->model_catalog_mvd_product->addProduct($this->request->post);
			
			/*添加全文索引*/
			if(strtoupper(substr(PHP_OS, 0, 3)) != 'WIN'){
				$this->load->model('catalog/xunsearch');

				$post_data = $this->request->post;
				$this->model_catalog_xunsearch->addDoc($pid,$post_data);
			}
			/*添加全文索引*/

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_model'])) {
				$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
			}
			
			//mvds
			if (isset($this->request->get['filter_vendor_name'])) {
				$url .= '&filter_vendor_name=' . urlencode(html_entity_decode($this->request->get['filter_vendor_name'], ENT_QUOTES, 'UTF-8'));
			}
			
			//商品编码
			if (isset($this->request->get['filter_product_code'])) {
				$url .= '&filter_product_code=' . urlencode(html_entity_decode($this->request->get['filter_product_code'], ENT_QUOTES, 'UTF-8'));
			}
			
			if (isset($this->request->get['filter_sku'])) {
				$url .= '&filter_sku=' . urlencode(html_entity_decode($this->request->get['filter_sku'], ENT_QUOTES, 'UTF-8'));
			}
			//mvde

			if (isset($this->request->get['filter_price'])) {
				$url .= '&filter_price=' . $this->request->get['filter_price'];
			}

			if (isset($this->request->get['filter_quantity'])) {
				$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getForm();
	}

	public function edit() {
		$this->load->language('catalog/mvd_product');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('catalog/mvd_product');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$post_data = $this->request->post;
			// var_dump($post_data);die();
			// if ($this->user->hasPermission('modify', 'catalog/product_price_change')) {
			// 	$product_price_change_permission = 1;
			// }else{
			// 	$product_price_change_permission = 0;
			// }

            // var_dump($post_data['clearance']);die();
			$product_info = $this->model_catalog_mvd_product->getProduct($this->request->get['product_id']);
			$product_specials = $this->model_catalog_mvd_product->getProductSpecials($this->request->get['product_id']);
			$dsp = $post_data['product_special'];
			$sp = $product_specials;
			$flag = false;
			foreach ($dsp as $key => $value) {
				// var_dump($value);
				 if (empty($value['product_special_id'])) {
					$flag = true;
				 	$comments = '新增特价:价格为'.$value['price'].',<br>开始时间为'.$value['date_start'].'<br>结束时间为'.$value['date_end'];
					$this->model_catalog_mvd_product->addStHistory($this->request->get['product_id'],$this->user->getId(),$comments);
				 }
			}
			for ($i=0; $i <count($dsp) ; $i++) { 
					if (($dsp[$i]['price'] != $sp[$i]['price'])||($dsp[$i]['priority'] != $sp[$i]['priority'])) {
						if (!empty($dsp[$i]['product_special_id'])) {
							$flag = true;
							$comments = '特价编号：'.$sp[$i]['product_special_id'];
							if ($dsp[$i]['price'] != $sp[$i]['price']) {
								$comments .= '<br>修改特价:原特价为'.$sp[$i]['price'].'修改为'.$dsp[$i]['price'];
								
							}
							if (strtotime($dsp[$i]['date_start']) != strtotime($sp[$i]['date_start'])) {
								$comments .= '<br>修改开始时间:原开始时间为'.$sp[$i]['date_start'].'修改为'.$dsp[$i]['date_start'];
								
							}
							if (strtotime($dsp[$i]['date_end']) != strtotime($sp[$i]['date_end'])) {
								$comments .= '<br>修改结束时间:原结束时间为'.$sp[$i]['date_end'].'修改为'.$dsp[$i]['date_end'];
								
							}
							if ($dsp[$i]['priority'] != $sp[$i]['priority']) {
								$comments .= '<br>修改优先级:原优先级为'.$sp[$i]['priority'].'修改为'.$dsp[$i]['priority'];
								
							}
							$this->model_catalog_mvd_product->addStHistory($this->request->get['product_id'],$this->user->getId(),$comments);
							}
						
					}
			}
			
			if($flag||($product_info['price'] != $post_data['price'])||($product_info['product_cost'] != $post_data['product_cost'])||($product_info['sale_price'] != $post_data['sale_price'])){
					if(($product_info['price'] != $post_data['price'])){
						$comments = '修改市场参考价：原市场参考价为'.$product_info['price'].',修改为'.$post_data['price'] ;
						$this->model_catalog_mvd_product->addStHistory($this->request->get['product_id'],$this->user->getId(),$comments);
					}

					if(($product_info['sale_price'] != $post_data['sale_price'])){
						$comments = '修改商品售价：原商品售价为'.$product_info['sale_price'].',修改为'.$post_data['sale_price'] ;
						$this->model_catalog_mvd_product->addStHistory($this->request->get['product_id'],$this->user->getId(),$comments);
					}
					if($product_info['product_cost'] != $post_data['product_cost']){
						$comments = '修改价格：原成本价格为'.$product_info['product_cost'].',修改为'.$post_data['product_cost'] ;
						$this->model_catalog_mvd_product->addStHistory($this->request->get['product_id'],$this->user->getId(),$comments);
					}

					$post_data['status'] =5;
				}
			// }
				// var_dump($post_data);die();
			$this->model_catalog_mvd_product->editProduct($this->request->get['product_id'], $post_data);
			// var_dump($post_data['clearance']);
			// var_dump($post_data['lack_status']);
			if ($post_data['clearance']=='on'||$post_data['lack_status']==3) {
				// echo 111;
                $clearqtyInfo = $this->model_catalog_mvd_product->getclearqty($this->request->get['product_id']);
                $clearqty = $clearqtyInfo['clearqty'];

                $procode = substr($clearqtyInfo['product_code'], 0, 10);
        		$this->load->model('stock/stocksearch');
        		// var_dump($procode);
            	$tmp = $this->model_stock_stocksearch->getsaleqty($procode,1);
            	// var_dump($tmp);
            	foreach ($tmp as $wh=>$qty) {
		            $saleqty += $qty;
		        }

            	// var_dump($saleqty);

             //    var_dump($clearqty);
             //    var_dump($proqty);
             //    die();
                $proqty = $clearqty-$saleqty;
        		M('product_option_value')->where(array('product_id' => $this->request->get['product_id']))->save(array('quantity' => $proqty));
        		// echo M('product_option_value')->getlastsql();die();

                
            }


			/*编辑全文索引*/
			if(strtoupper(substr(PHP_OS, 0, 3)) != 'WIN'){
				$this->load->model('catalog/xunsearch');
				$this->model_catalog_xunsearch->editDoc($this->request->get['product_id'],$post_data);
			}
			/*编辑全文索引*/
			
			/*上下架自动发送站内消息*/
			/*$old_status = $this->request->post['pending_status'];
			$new_status = $post_data['status'];
			if($new_status != $old_status){

				$this->load->model('marketing/message');
				$mdata = array(
					'product_id' => $this->request->get['product_id']
				);
				
				if($new_status == 1){
					$this->model_marketing_message->sendAutoMessage(3,$mdata); //发送上架消息
				}
				else{
					$this->model_marketing_message->sendAutoMessage(2,$mdata); //发送下架消息
				}

			}*/
			/*上下架自动发送站内消息*/
			
			//mvds
			if ($this->config->get('mvd_product_edit_approval')) {
				if ($this->config->get('mvd_product_notification')) {
					if (!empty($this->request->post['product_name']) && ($this->request->post['status'] == '1') && ($this->request->post['pending_status'] == '5')) {
						$this->approve_notification($this->request->post['product_name'],$this->request->post['vendor']);
					}
				}
			}
			//mvde
			
			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_model'])) {
				$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
			}
			
			//mvds
			if (isset($this->request->get['filter_vendor_name'])) {
				$url .= '&filter_vendor_name=' . urlencode(html_entity_decode($this->request->get['filter_vendor_name'], ENT_QUOTES, 'UTF-8'));
			}
			
			//商品编码
			if (isset($this->request->get['filter_product_code'])) {
				$url .= '&filter_product_code=' . urlencode(html_entity_decode($this->request->get['filter_product_code'], ENT_QUOTES, 'UTF-8'));
			}
			
			if (isset($this->request->get['filter_sku'])) {
				$url .= '&filter_sku=' . urlencode(html_entity_decode($this->request->get['filter_sku'], ENT_QUOTES, 'UTF-8'));
			}
			//mvde
			if (isset($this->request->get['filter_stock'])) {
				$url .= '&filter_stock=' . urlencode(html_entity_decode($this->request->get['filter_stock'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_price'])) {
				$url .= '&filter_price=' . $this->request->get['filter_price'];
			}

			if (isset($this->request->get['filter_quantity'])) {
				$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}
			$this->model_catalog_mvd_product->addStHistory($this->request->get['product_id'],$this->user->getId(),'操作了商品');
			$this->response->redirect($this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getForm();
	}

	public function delete() {
        return false;

		$this->load->language('catalog/mvd_product');
		$this->load->model('catalog/xunsearch');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('catalog/mvd_product');

		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $product_id) {
				$this->model_catalog_mvd_product->deleteProduct($product_id);

				//删除全文索引
				if(strtoupper(substr(PHP_OS, 0, 3)) != 'WIN'){
					$this->model_catalog_xunsearch->delDoc($product_id);
				}

			}

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_model'])) {
				$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
			}
			
			//mvds
			if (isset($this->request->get['filter_vendor_name'])) {
				$url .= '&filter_vendor_name=' . urlencode(html_entity_decode($this->request->get['filter_vendor_name'], ENT_QUOTES, 'UTF-8'));
			}
			
			//商品编码
			if (isset($this->request->get['filter_product_code'])) {
				$url .= '&filter_product_code=' . urlencode(html_entity_decode($this->request->get['filter_product_code'], ENT_QUOTES, 'UTF-8'));
			}
			
			if (isset($this->request->get['filter_sku'])) {
				$url .= '&filter_sku=' . urlencode(html_entity_decode($this->request->get['filter_sku'], ENT_QUOTES, 'UTF-8'));
			}
			//mvde

			if (isset($this->request->get['filter_price'])) {
				$url .= '&filter_price=' . $this->request->get['filter_price'];
			}

			if (isset($this->request->get['filter_quantity'])) {
				$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getList();
	}

	public function copy() {
		$this->load->language('catalog/mvd_product');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('catalog/mvd_product');

		if (isset($this->request->post['selected']) && $this->validateCopy()) {
			foreach ($this->request->post['selected'] as $product_id) {
				$this->model_catalog_mvd_product->copyProduct($product_id);
			}

			$this->session->data['success'] = $this->language->get('text_success');

			$url = '';

			if (isset($this->request->get['filter_name'])) {
				$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
			}

			if (isset($this->request->get['filter_model'])) {
				$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
			}
			
			//mvds
			if (isset($this->request->get['filter_vendor_name'])) {
				$url .= '&filter_vendor_name=' . urlencode(html_entity_decode($this->request->get['filter_vendor_name'], ENT_QUOTES, 'UTF-8'));
			}
			
			//商品编码
			if (isset($this->request->get['filter_product_code'])) {
				$url .= '&filter_product_code=' . urlencode(html_entity_decode($this->request->get['filter_product_code'], ENT_QUOTES, 'UTF-8'));
			}
			
			if (isset($this->request->get['filter_sku'])) {
				$url .= '&filter_sku=' . urlencode(html_entity_decode($this->request->get['filter_sku'], ENT_QUOTES, 'UTF-8'));
			}
			//mvde

			if (isset($this->request->get['filter_price'])) {
				$url .= '&filter_price=' . $this->request->get['filter_price'];
			}

			if (isset($this->request->get['filter_quantity'])) {
				$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
			}

			if (isset($this->request->get['filter_status'])) {
				$url .= '&filter_status=' . $this->request->get['filter_status'];
			}

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}

			if (isset($this->request->get['page'])) {
				$url .= '&page=' . $this->request->get['page'];
			}

			$this->response->redirect($this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . $url, 'SSL'));
		}

		$this->getList();
	}

	protected function getList() {
		if (isset($this->request->get['filter_name'])) {
			$filter_name = $this->request->get['filter_name'];
		} else {
			$filter_name = null;
		}

		if (isset($this->request->get['filter_model'])) {
			$filter_model = $this->request->get['filter_model'];
		} else {
			$filter_model = null;
		}

		if (isset($this->request->get['filter_price'])) {
			$filter_price = $this->request->get['filter_price'];
		} else {
			$filter_price = null;
		}

		if (isset($this->request->get['filter_quantity'])) {
			$filter_quantity = $this->request->get['filter_quantity'];
		} else {
			$filter_quantity = null;
		}

		if (isset($this->request->get['filter_status'])) {
			$filter_status = $this->request->get['filter_status'];
		} else {
			$filter_status = null;
		}
		
		//mvds
		if (isset($this->request->get['filter_sku'])) {
			$filter_sku = $this->request->get['filter_sku'];
		} else {
			$filter_sku = null;
		}
		
		//商品编码
		if (isset($this->request->get['filter_product_code'])) {
			$filter_product_code = $this->request->get['filter_product_code'];
		} else {
			$filter_product_code = null;
		}

		//有库存
		if (isset($this->request->get['filter_stock'])) {
			$filter_stock = $this->request->get['filter_stock'];
		} else {
			$filter_stock = null;
		}
			
		if (isset($this->request->get['filter_vendor'])) {
			$filter_vendor = $this->request->get['filter_vendor'];
		} else {
			$filter_vendor = NULL;
		}
			
		if (isset($this->request->get['filter_vendor_name'])) {
			$filter_vendor_name = $this->request->get['filter_vendor_name'];
		} else {
			$filter_vendor_name = NULL;
		}
		//mvde

		if (isset($this->request->get['sort'])) {
			$sort = $this->request->get['sort'];
		} else {
			// $sort = 'pd.name';
			// $sort = 'p.date_added';
			$sort = 'p.status';
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'DESC';
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}
		
		//商品编码
		if (isset($this->request->get['filter_product_code'])) {
			$url .= '&filter_product_code=' . urlencode(html_entity_decode($this->request->get['filter_product_code'], ENT_QUOTES, 'UTF-8'));
		}

		//有库存
		if (isset($this->request->get['filter_stock'])) {
			$url .= '&filter_stock=' . urlencode(html_entity_decode($this->request->get['filter_stock'], ENT_QUOTES, 'UTF-8'));
		}
		
		//mvds
		if (isset($this->request->get['filter_sku'])) {
			$url .= '&filter_sku=' . urlencode(html_entity_decode($this->request->get['filter_sku'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_stock'])) {
			$url .= '&filter_stock=' . urlencode(html_entity_decode($this->request->get['filter_stock'], ENT_QUOTES, 'UTF-8'));
		}
			
		if (isset($this->request->get['filter_vendor_name'])) {
			$url .= '&filter_vendor_name=' . urlencode(html_entity_decode($this->request->get['filter_vendor_name'], ENT_QUOTES, 'UTF-8'));
		}
			
		if (isset($this->request->get['filter_vendor'])) {
			$url .= '&filter_vendor=' . urlencode(html_entity_decode($this->request->get['filter_vendor'], ENT_QUOTES, 'UTF-8'));
		}
		//mvde

		if (isset($this->request->get['filter_price'])) {
			$url .= '&filter_price=' . $this->request->get['filter_price'];
		}

		if (isset($this->request->get['filter_quantity'])) {
			$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);

		$data['add'] = $this->url->link('catalog/mvd_product/add', 'token=' . $this->session->data['token'] . $url, 'SSL');
		$data['copy'] = $this->url->link('catalog/mvd_product/copy', 'token=' . $this->session->data['token'] . $url, 'SSL');
		$data['delete'] = $this->url->link('catalog/mvd_product/delete', 'token=' . $this->session->data['token'] . $url, 'SSL');

		$data['products'] = array();

		$filter_data = array(
			'filter_name'	  => $filter_name,
			'filter_model'	  => $filter_model,
			'filter_price'	  => $filter_price,
			//mvds
			'filter_sku'	 	   => $filter_sku,
			'filter_stock'	 	   => $filter_stock,
			'filter_product_code' => $filter_product_code,
			'filter_stock' => $filter_stock,
			'filter_vendor'   	   => $filter_vendor, 
			'filter_vendor_name'   => $filter_vendor_name,
			//mvde
			'filter_quantity' => $filter_quantity,
			'filter_status'   => $filter_status,
			'sort'            => $sort,
			'order'           => $order,
			'start'           => ($page - 1) * $this->config->get('config_limit_admin'),
			'limit'           => $this->config->get('config_limit_admin')
		);

		$this->load->model('tool/image');
        $this->load->model('stock/stocksearch');

		$product_total = $this->model_catalog_mvd_product->getTotalProducts($filter_data);
		$results = $this->model_catalog_mvd_product->getProducts($filter_data);
		//mvds
		$data['vendors'] = $this->model_catalog_mvd_product->getVendors();
		$data['user_group_id'] = $this->model_catalog_mvd_product->userGroup($this->user->getId());
		//mvde
		
		foreach ($results as $result) {
            if (is_file(DIR_IMAGE . $result['image'])) {
				$image = $this->model_tool_image->resize($result['image'], 40, 40);
			} else {
				$image = $this->model_tool_image->resize('no_image.png', 40, 40);
			}

			$special=0;
			$product_specials = $this->model_catalog_mvd_product->getgroupProductSpecials($result['product_id'],$data['user_group_id']);

			foreach ($product_specials  as $product_special) {
				if (($product_special['date_start'] == '0000-00-00' || strtotime($product_special['date_start']) < time()) && ($product_special['date_end'] == '0000-00-00' || strtotime($product_special['date_end']) > time())) {
				
					$special = $product_special['price'];

					break;
				}
			}
			if ((int)$special==0) {
				// echo 11;
				$special = $result['sale_price'];
				
			}
			// var_dump($special);
			//mvds
			if ($result['status'] == 5) {
				$status = $this->language->get('txt_pending_approval');
			}elseif ($result['status'] ==3) {
				$status = '初始';
			} elseif ($result['status']) {
				$status = $this->language->get('text_enabled');
			} else {
				$status = $this->language->get('text_disabled');
			}

			//mvde
            $productStock = $this->model_stock_stocksearch->getGatherQtyByProductCode($result['product_code']);
            $productbuy = $this->model_stock_stocksearch->getGatherBuyQtyByProductCode($result['product_code']);
            $dcycle = $this->model_stock_stocksearch->getDeliveryCycle($result['product_code']);
            $saleqty = $this->model_stock_stocksearch->getsaleqty($result['product_code']);
            // var_dump($saleqty);
            $productquty = $this->model_catalog_mvd_product->getoptionvalue($result['product_id']);
           
            $data['products'][] = array(
				'product_id' => $result['product_id'],
				'image'      => $image,
				'name'       => $result['name'],
				'model'      => $result['model'],
				'price'      => $result['price'],
				'special'    => $special,
				//mvds
				'sku'      	 => $result['sku'],
				'product_code'      	 => $result['product_code'],
				'vendor_name'=> $result['vendor_name'],
				'status'     => $status,
				'status_id'     => $result['status'],
				//mvde
				'quantity'   => $productquty,
                'availableQty' => $productStock['availableQty'],
                'safeQuantity' => $productStock['safeQuantity'],
                'buyqty' => $productbuy,
                'dcycle' => $dcycle,
                'saleqty' => $saleqty,
                'is_shelf_product' => $result['is_shelf_product']?'是':'否',
				//'status'     => ($result['status']) ? $this->language->get('text_enabled') : $this->language->get('text_disabled'),
				'edit'       => $this->url->link('catalog/mvd_product/edit', 'token=' . $this->session->data['token'] . '&product_id=' . $result['product_id'] . $url, 'SSL')
			);
		}

		$data['heading_title'] = $this->language->get('heading_title');
		
		$data['text_list'] = $this->language->get('text_list');
		$data['text_enabled'] = $this->language->get('text_enabled');
		$data['text_disabled'] = $this->language->get('text_disabled');
		$data['text_no_results'] = $this->language->get('text_no_results');
		$data['text_confirm'] = $this->language->get('text_confirm');
		//mvds
		$data['column_vendor'] = $this->language->get('column_vendor');
		$data['column_sku'] = $this->language->get('column_sku');
		$data['entry_vendor_name'] = $this->language->get('entry_vendor_name');
		$data['entry_sku'] = $this->language->get('entry_sku');
		$data['txt_pending_approval'] = $this->language->get('txt_pending_approval');
		//mvde

		$data['column_image'] = $this->language->get('column_image');
		$data['column_name'] = $this->language->get('column_name');
		$data['column_model'] = $this->language->get('column_model');
		$data['column_price'] = $this->language->get('column_price');
		$data['column_quantity'] = $this->language->get('column_quantity');
		$data['column_status'] = $this->language->get('column_status');
		$data['column_action'] = $this->language->get('column_action');
		$data['entry_name'] = $this->language->get('entry_name');
		$data['entry_model'] = $this->language->get('entry_model');
		$data['entry_price'] = $this->language->get('entry_price');
		$data['entry_quantity'] = $this->language->get('entry_quantity');
		$data['entry_status'] = $this->language->get('entry_status');

		$data['button_copy'] = $this->language->get('button_copy');
		$data['button_add'] = $this->language->get('button_add');
		$data['button_edit'] = $this->language->get('button_edit');
		$data['button_delete'] = $this->language->get('button_delete');
		$data['button_filter'] = $this->language->get('button_filter');

		$data['token'] = $this->session->data['token'];

		//商品编码
		$data['entry_product_code'] = $this->language->get('entry_product_code');

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->session->data['success'])) {
			$data['success'] = $this->session->data['success'];

			unset($this->session->data['success']);
		} else {
			$data['success'] = '';
		}

		if (isset($this->request->post['selected'])) {
			$data['selected'] = (array)$this->request->post['selected'];
		} else {
			$data['selected'] = array();
		}

		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}
		
		//mvds
		if (isset($this->request->get['filter_stock'])) {
			$url .= '&filter_stock=' . urlencode(html_entity_decode($this->request->get['filter_stock'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_sku'])) {
			$url .= '&filter_sku=' . urlencode(html_entity_decode($this->request->get['filter_sku'], ENT_QUOTES, 'UTF-8'));
		}
		
		//商品编码
		if (isset($this->request->get['filter_product_code'])) {
			$url .= '&filter_product_code=' . urlencode(html_entity_decode($this->request->get['filter_product_code'], ENT_QUOTES, 'UTF-8'));
		}

		//有库存
		if (isset($this->request->get['filter_stock'])) {
			$url .= '&filter_stock=' . urlencode(html_entity_decode($this->request->get['filter_stock'], ENT_QUOTES, 'UTF-8'));
		}
			
		if (isset($this->request->get['filter_vendor_name'])) {
			$url .= '&filter_vendor_name=' . urlencode(html_entity_decode($this->request->get['filter_vendor_name'], ENT_QUOTES, 'UTF-8'));
		}
			
		if (isset($this->request->get['filter_vendor'])) {
			$url .= '&filter_vendor=' . urlencode(html_entity_decode($this->request->get['filter_vendor'], ENT_QUOTES, 'UTF-8'));
		}
		//mvde

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_price'])) {
			$url .= '&filter_price=' . $this->request->get['filter_price'];
		}

		if (isset($this->request->get['filter_quantity'])) {
			$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if ($order == 'ASC') {
			$url .= '&order=DESC';
		} else {
			$url .= '&order=ASC';
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['sort_name'] = $this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . '&sort=pd.name' . $url, 'SSL');
		$data['sort_model'] = $this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . '&sort=p.model' . $url, 'SSL');
		$data['sort_price'] = $this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . '&sort=p.price' . $url, 'SSL');
		$data['sort_quantity'] = $this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . '&sort=p.quantity' . $url, 'SSL');
		$data['sort_status'] = $this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . '&sort=p.status' . $url, 'SSL');
		$data['sort_order'] = $this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . '&sort=p.sort_order' . $url, 'SSL');
		//mvds
		$data['sort_sku'] = $this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . '&sort=p.sku' . $url, 'SSL');
		$data['sort_vendor_name'] = $this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . '&sort=vds.vendor_id' . $url, 'SSL');
		//mvde
		
		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}
		
		//mvds
		if (isset($this->request->get['filter_sku'])) {
			$url .= '&filter_sku=' . urlencode(html_entity_decode($this->request->get['filter_sku'], ENT_QUOTES, 'UTF-8'));
		}
		
		//商品编码
		if (isset($this->request->get['filter_product_code'])) {
			$url .= '&filter_product_code=' . urlencode(html_entity_decode($this->request->get['filter_product_code'], ENT_QUOTES, 'UTF-8'));
		}

		//有库存
		if (isset($this->request->get['filter_stock'])) {
			$url .= '&filter_stock=' . urlencode(html_entity_decode($this->request->get['filter_stock'], ENT_QUOTES, 'UTF-8'));
		}
			
		if (isset($this->request->get['filter_vendor_name'])) {
			$url .= '&filter_vendor_name=' . urlencode(html_entity_decode($this->request->get['filter_vendor_name'], ENT_QUOTES, 'UTF-8'));
		}
		//mvde

		if (isset($this->request->get['filter_price'])) {
			$url .= '&filter_price=' . $this->request->get['filter_price'];
		}

		if (isset($this->request->get['filter_quantity'])) {
			$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		$pagination = new Pagination();
		$pagination->total = $product_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_limit_admin');
		$pagination->url = $this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

		$data['pagination'] = $pagination->render();

		$data['results'] = sprintf($this->language->get('text_pagination'), ($product_total) ? (($page - 1) * $this->config->get('config_limit_admin')) + 1 : 0, ((($page - 1) * $this->config->get('config_limit_admin')) > ($product_total - $this->config->get('config_limit_admin'))) ? $product_total : ((($page - 1) * $this->config->get('config_limit_admin')) + $this->config->get('config_limit_admin')), $product_total, ceil($product_total / $this->config->get('config_limit_admin')));

		$data['filter_name'] = $filter_name;
		$data['filter_model'] = $filter_model;
		//mvds
		$data['filter_sku'] = $filter_sku;
		$data['filter_product_code'] = $filter_product_code;
		$data['filter_stock'] = $filter_stock;
		$data['filter_vendor_name'] = $filter_vendor_name;
		//mvde
		$data['filter_price'] = $filter_price;
		$data['filter_quantity'] = $filter_quantity;
		$data['filter_status'] = $filter_status;

		$data['sort'] = $sort;
		$data['order'] = $order;

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');
		
		$this->response->setOutput($this->load->view('catalog/mvd_product_list.tpl', $data));
	}

	protected function getForm() {
		$data['heading_title'] = $this->language->get('heading_title');
		
		$data['text_form'] = !isset($this->request->get['product_id']) ? $this->language->get('text_add') : $this->language->get('text_edit');
		$data['text_enabled'] = $this->language->get('text_enabled');
		$data['text_disabled'] = $this->language->get('text_disabled');
		$data['text_none'] = $this->language->get('text_none');
		$data['text_yes'] = $this->language->get('text_yes');
		$data['text_no'] = $this->language->get('text_no');
		$data['text_plus'] = $this->language->get('text_plus');
		$data['text_minus'] = $this->language->get('text_minus');
		$data['text_default'] = $this->language->get('text_default');
		$data['text_option'] = $this->language->get('text_option');
		$data['text_option_value'] = $this->language->get('text_option_value');
		$data['text_select'] = $this->language->get('text_select');
		$data['text_percent'] = $this->language->get('text_percent');
		$data['text_amount'] = $this->language->get('text_amount');

		$data['entry_name'] = $this->language->get('entry_name');
		$data['entry_description'] = $this->language->get('entry_description');
		$data['entry_meta_title'] = $this->language->get('entry_meta_title');
		$data['entry_meta_description'] = $this->language->get('entry_meta_description');
		$data['entry_meta_keyword'] = $this->language->get('entry_meta_keyword');
		$data['entry_keyword'] = $this->language->get('entry_keyword');
		$data['entry_model'] = $this->language->get('entry_model');
		$data['entry_sku'] = $this->language->get('entry_sku');
		$data['entry_middle_package'] = $this->language->get('entry_middle_package');
		$data['entry_upc'] = $this->language->get('entry_upc');
		$data['entry_ean'] = $this->language->get('entry_ean');
		$data['entry_jan'] = $this->language->get('entry_jan');
		$data['entry_isbn'] = $this->language->get('entry_isbn');
		$data['entry_mpn'] = $this->language->get('entry_mpn');
		$data['entry_location'] = $this->language->get('entry_location');
		$data['entry_minimum'] = $this->language->get('entry_minimum');
		$data['entry_shipping'] = $this->language->get('entry_shipping');
		$data['entry_date_available'] = $this->language->get('entry_date_available');
		$data['entry_quantity'] = $this->language->get('entry_quantity');
		$data['entry_stock_status'] = $this->language->get('entry_stock_status');
		$data['entry_price'] = $this->language->get('entry_price');
		$data['entry_tax_class'] = $this->language->get('entry_tax_class');
		$data['entry_points'] = $this->language->get('entry_points');
		$data['entry_option_points'] = $this->language->get('entry_option_points');
		$data['entry_subtract'] = $this->language->get('entry_subtract');
		$data['entry_weight_class'] = $this->language->get('entry_weight_class');
		$data['entry_weight'] = $this->language->get('entry_weight');
		$data['entry_dimension'] = $this->language->get('entry_dimension');
		$data['entry_length_class'] = $this->language->get('entry_length_class');
		$data['entry_length'] = $this->language->get('entry_length');
		$data['entry_width'] = $this->language->get('entry_width');
		$data['entry_height'] = $this->language->get('entry_height');
		$data['entry_image'] = $this->language->get('entry_image');
		$data['entry_store'] = $this->language->get('entry_store');
		$data['entry_manufacturer'] = $this->language->get('entry_manufacturer');
		$data['entry_download'] = $this->language->get('entry_download');
		$data['entry_category'] = $this->language->get('entry_category');
		$data['entry_filter'] = $this->language->get('entry_filter');
		$data['entry_related'] = $this->language->get('entry_related');
		$data['entry_attribute'] = $this->language->get('entry_attribute');
		$data['entry_text'] = $this->language->get('entry_text');
		$data['entry_option'] = $this->language->get('entry_option');
		$data['entry_option_value'] = $this->language->get('entry_option_value');
		$data['entry_required'] = $this->language->get('entry_required');
		$data['entry_sort_order'] = $this->language->get('entry_sort_order');
		$data['entry_status'] = $this->language->get('entry_status');
		$data['entry_date_start'] = $this->language->get('entry_date_start');
		$data['entry_date_end'] = $this->language->get('entry_date_end');
		$data['entry_priority'] = $this->language->get('entry_priority');
		$data['entry_tag'] = $this->language->get('entry_tag');
		$data['entry_customer_group'] = $this->language->get('entry_customer_group');
		$data['entry_reward'] = $this->language->get('entry_reward');
		$data['entry_layout'] = $this->language->get('entry_layout');
		$data['entry_recurring'] = $this->language->get('entry_recurring');
        $data['entry_type'] = $this->language->get('entry_type');

		$data['help_keyword'] = $this->language->get('help_keyword');
		$data['help_sku'] = $this->language->get('help_sku');
		$data['help_middle_package'] = $this->language->get('help_middle_package');
		$data['help_upc'] = $this->language->get('help_upc');
		$data['help_ean'] = $this->language->get('help_ean');
		$data['help_jan'] = $this->language->get('help_jan');
		$data['help_isbn'] = $this->language->get('help_isbn');
		$data['help_mpn'] = $this->language->get('help_mpn');
		$data['help_minimum'] = $this->language->get('help_minimum');
		$data['help_manufacturer'] = $this->language->get('help_manufacturer');
		$data['help_stock_status'] = $this->language->get('help_stock_status');
		$data['help_points'] = $this->language->get('help_points');
		$data['help_category'] = $this->language->get('help_category');
		$data['help_filter'] = $this->language->get('help_filter');
		$data['help_download'] = $this->language->get('help_download');
		$data['help_related'] = $this->language->get('help_related');
		$data['help_tag'] = $this->language->get('help_tag');

		$data['button_save'] = $this->language->get('button_save');
		$data['button_cancel'] = $this->language->get('button_cancel');
		$data['button_attribute_add'] = $this->language->get('button_attribute_add');
		$data['button_option_add'] = $this->language->get('button_option_add');
		$data['button_option_value_add'] = $this->language->get('button_option_value_add');
		$data['button_discount_add'] = $this->language->get('button_discount_add');
		$data['button_special_add'] = $this->language->get('button_special_add');
		$data['button_image_add'] = $this->language->get('button_image_add');
		$data['button_remove'] = $this->language->get('button_remove');
		$data['button_recurring_add'] = $this->language->get('button_recurring_add');

		$data['tab_general'] = $this->language->get('tab_general');
		$data['tab_data'] = $this->language->get('tab_data');
		$data['tab_attribute'] = $this->language->get('tab_attribute');
		$data['tab_option'] = $this->language->get('tab_option');
		$data['tab_recurring'] = $this->language->get('tab_recurring');
		$data['tab_discount'] = $this->language->get('tab_discount');
		$data['tab_special'] = $this->language->get('tab_special');
		$data['tab_image'] = $this->language->get('tab_image');
		$data['tab_links'] = $this->language->get('tab_links');
		$data['tab_reward'] = $this->language->get('tab_reward');
		$data['tab_design'] = $this->language->get('tab_design');
		$data['tab_openbay'] = $this->language->get('tab_openbay');
		$data['tab_product_group'] = $this->language->get('tab_product_group');
		
		//mvds
		$data['entry_vendor_country_origin'] = $this->language->get('entry_vendor_country_origin');
		$data['entry_vendor_product_cost'] = $this->language->get('entry_vendor_product_cost');
		$data['entry_vendor_shipping_method'] = $this->language->get('entry_vendor_shipping_method');
		$data['entry_vendor_preferred_shipping_method'] = $this->language->get('entry_vendor_preferred_shipping_method');
		$data['entry_vendor_shipping_cost'] = $this->language->get('entry_vendor_shipping_cost');
		$data['entry_vendor_total'] = $this->language->get('entry_vendor_total');
		$data['entry_vendor_company'] = $this->language->get('entry_vendor_company');
		$data['entry_vendor_description'] = $this->language->get('entry_vendor_description');
		$data['entry_vendor_contact_name'] = $this->language->get('entry_vendor_contact_name');
		$data['entry_vendor_telephone'] = $this->language->get('entry_vendor_telephone');
		$data['entry_vendor_fax'] = $this->language->get('entry_vendor_fax');
		$data['entry_vendor_email'] = $this->language->get('entry_vendor_email');
		$data['entry_vendor_paypal_email'] = $this->language->get('entry_vendor_paypal_email');
		$data['entry_vendor_address'] = $this->language->get('entry_vendor_address');
		$data['entry_vendor_country_zone'] = $this->language->get('entry_vendor_country_zone');
		$data['entry_vendor_store_url'] = $this->language->get('entry_vendor_store_url');
		$data['entry_vendor_product_url'] = $this->language->get('entry_vendor_product_url');
		$data['entry_vendor_name'] = $this->language->get('entry_vendor_name');
		$data['entry_vendor_wholesale'] = $this->language->get('entry_vendor_wholesale');
		$data['entry_shipping_rate'] = $this->language->get('entry_shipping_rate');
		$data['tab_vendor'] = $this->language->get('tab_vendor');
		$data['tab_shipping'] = $this->language->get('tab_shipping');
		$data['txt_pending_approval'] = $this->language->get('txt_pending_approval');
			
		$data['entry_shipping_courier'] = $this->language->get('entry_shipping_courier');
		$data['entry_shipping_cost'] = $this->language->get('entry_shipping_cost');
		$data['entry_shipping_geozone'] = $this->language->get('entry_shipping_geozone');
		$data['button_add_shipping'] = $this->language->get('button_add_shipping');
		
		$data['help_vendor_country_origin'] = $this->language->get('help_vendor_country_origin');
		$data['help_vendor_shipping_method'] = $this->language->get('help_vendor_shipping_method');
		$data['help_vendor_preferred_shipping_method'] = $this->language->get('help_vendor_preferred_shipping_method');
		$data['help_vendor_total'] = $this->language->get('help_vendor_total');

		//商品分类
		$data['entry_product_class'] = $this->language->get('entry_product_class');
		$data['entry_is_single'] = $this->language->get('entry_is_single');

		//商品编码
		$data['entry_product_code'] = $this->language->get('entry_product_code');

		if (isset($this->error['warning'])) {
			$data['error_warning'] = $this->error['warning'];
		} else {
			$data['error_warning'] = '';
		}

		if (isset($this->error['name'])) {
			$data['error_name'] = $this->error['name'];
		} else {
			$data['error_name'] = array();
		}

		if (isset($this->error['product_class1'])) {
			$data['error_product_class1'] = $this->error['product_class1'];
		} else {
			$data['error_product_class1'] = array();
		}

		if (isset($this->error['product_class2'])) {
			$data['error_product_class2'] = $this->error['product_class2'];
		} else {
			$data['error_product_class2'] = array();
		}

		if (isset($this->error['product_class3'])) {
			$data['error_product_class3'] = $this->error['product_class3'];
		} else {
			$data['error_product_class3'] = array();
		}

		if (isset($this->error['product_code'])) {
			$data['error_product_code'] = $this->error['product_code'];
		} else {
			$data['error_product_code'] = array();
		}

		if (isset($this->error['meta_title'])) {
			$data['error_meta_title'] = $this->error['meta_title'];
		} else {
			$data['error_meta_title'] = array();
		}

		if (isset($this->error['model'])) {
			$data['error_model'] = $this->error['model'];
		} else {
			$data['error_model'] = '';
		}

		if (isset($this->error['vendor'])) {
			$data['error_vendor'] = $this->error['vendor'];
		} else {
			$data['error_vendor'] = '';
		}

		if (isset($this->error['price'])) {
			$data['error_price'] = $this->error['price'];
		} else {
			$data['error_price'] = '';
		}

		if (isset($this->error['sale_price'])) {
			$data['error_sale_price'] = '请填写商品售价';
		} else {
			$data['error_sale_price'] = '';
		}

		if (isset($this->error['product_special'])) {
			$data['error_product_special'] = $this->error['product_special'];
		} else {
			$data['error_product_special'] = '';
		}

		if (isset($this->error['product_option'])) {
			$data['error_product_option'] = $this->error['product_option'];
		} else {
			$data['error_product_option'] = '';
		}

		if (isset($this->error['product_cost'])) {
			$data['error_product_cost'] = $this->error['product_cost'];
		} else {
			$data['error_product_cost'] = '';
		}

		if (isset($this->error['date_available'])) {
			$data['error_date_available'] = $this->error['date_available'];
		} else {
			$data['error_date_available'] = '';
		}
		
		if (isset($this->error['keyword'])) {
			$data['error_keyword'] = $this->error['keyword'];
		} else {
			$data['error_keyword'] = '';
		}

		$url = '';

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . urlencode(html_entity_decode($this->request->get['filter_name'], ENT_QUOTES, 'UTF-8'));
		}
		
		//mvds
		if (isset($this->request->get['filter_sku'])) {
			$url .= '&filter_sku=' . urlencode(html_entity_decode($this->request->get['filter_sku'], ENT_QUOTES, 'UTF-8'));
		}
		
		//商品编码
		if (isset($this->request->get['filter_product_code'])) {
			$url .= '&filter_product_code=' . urlencode(html_entity_decode($this->request->get['filter_product_code'], ENT_QUOTES, 'UTF-8'));
		}

		//有库存
		if (isset($this->request->get['filter_stock'])) {
			$url .= '&filter_stock=' . urlencode(html_entity_decode($this->request->get['filter_stock'], ENT_QUOTES, 'UTF-8'));
		}
			
		if (isset($this->request->get['filter_vendor_name'])) {
			$url .= '&filter_vendor_name=' . urlencode(html_entity_decode($this->request->get['filter_vendor_name'], ENT_QUOTES, 'UTF-8'));
		}
			
		if (isset($this->request->get['filter_vendor'])) {
			$url .= '&filter_vendor=' . urlencode(html_entity_decode($this->request->get['filter_vendor'], ENT_QUOTES, 'UTF-8'));
		}
		//mvde

		if (isset($this->request->get['filter_model'])) {
			$url .= '&filter_model=' . urlencode(html_entity_decode($this->request->get['filter_model'], ENT_QUOTES, 'UTF-8'));
		}

		if (isset($this->request->get['filter_price'])) {
			$url .= '&filter_price=' . $this->request->get['filter_price'];
		}

		if (isset($this->request->get['filter_sale_price'])) {
			$url .= '&filter_sale_price=' . $this->request->get['filter_sale_price'];
		}

		if (isset($this->request->get['filter_quantity'])) {
			$url .= '&filter_quantity=' . $this->request->get['filter_quantity'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['sort'])) {
			$url .= '&sort=' . $this->request->get['sort'];
		}

		if (isset($this->request->get['order'])) {
			$url .= '&order=' . $this->request->get['order'];
		}

		if (isset($this->request->get['page'])) {
			$url .= '&page=' . $this->request->get['page'];
		}

		$data['breadcrumbs'] = array();

		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('text_home'),
			'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], 'SSL')
		);
		
		$data['breadcrumbs'][] = array(
			'text' => $this->language->get('heading_title'),
			'href' => $this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . $url, 'SSL')
		);

		if (!isset($this->request->get['product_id'])) {
			$data['action'] = $this->url->link('catalog/mvd_product/add', 'token=' . $this->session->data['token'] . $url, 'SSL');
		} else {
			$data['action'] = $this->url->link('catalog/mvd_product/edit', 'token=' . $this->session->data['token'] . '&product_id=' . $this->request->get['product_id'] . $url, 'SSL');
		}

		$data['cancel'] = $this->url->link('catalog/mvd_product', 'token=' . $this->session->data['token'] . $url, 'SSL');

		if (isset($this->request->get['product_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
			$product_info = $this->model_catalog_mvd_product->getProduct($this->request->get['product_id']);
		}

		$data['token'] = $this->session->data['token'];

		/*获取商品分类*/
		$parent_id = 0;
		$class1 = $this->model_catalog_mvd_product->getCategoryClass($parent_id);
		$data['class1'] = $class1;
		/*获取商品分类*/

		$this->load->model('localisation/language');

		$data['languages'] = $this->model_localisation_language->getLanguages();

		if (isset($this->request->post['product_description'])) {
			$data['product_description'] = $this->request->post['product_description'];
		} elseif (isset($this->request->get['product_id'])) {
			$data['product_description'] = $this->model_catalog_mvd_product->getProductDescriptions($this->request->get['product_id']);
		} else {
			$data['product_description'] = array();
		}

		if (isset($this->request->post['image'])) {
			$data['image'] = $this->request->post['image'];
		} elseif (!empty($product_info)) {
			$data['image'] = $product_info['image'];
		} else {
			$data['image'] = '';
		}

		$this->load->model('tool/image');

		if (isset($this->request->post['image']) && is_file(DIR_IMAGE . $this->request->post['image'])) {
			$data['thumb'] = $this->model_tool_image->resize($this->request->post['image'], 100, 100);
		} elseif (!empty($product_info) && is_file(DIR_IMAGE . $product_info['image'])) {
			$data['thumb'] = $this->model_tool_image->resize($product_info['image'], 100, 100);
		} else {
			$data['thumb'] = $this->model_tool_image->resize('no_image.png', 100, 100);
		}

		$data['placeholder'] = $this->model_tool_image->resize('no_image.png', 100, 100);
		
		if (isset($this->request->post['model'])) {
			$data['model'] = $this->request->post['model'];
		} elseif (!empty($product_info)) {
			$data['model'] = $product_info['model'];
		} else {
			$data['model'] = '';
		}

		if (isset($this->request->post['is_single'])) {
			$data['is_single'] = $this->request->post['is_single'];
		} elseif (!empty($product_info)) {
			$data['is_single'] = $product_info['is_single'];
		} else {
			$data['is_single'] = 1;
		}

		if (isset($this->request->post['is_part'])) {
			$data['is_part'] = $this->request->post['is_part'];
		} elseif (!empty($product_info)) {
			$data['is_part'] = $product_info['is_part'];
		} else {
			$data['is_part'] = 0;
		}


		if (isset($this->request->post['lack_reason'])) {
			$data['lack_reason'] = $this->request->post['lack_reason'];
		} elseif (!empty($product_info)) {
			$data['lack_reason'] = $product_info['lack_reason'];
		} else {
			$data['lack_reason'] = 1;
		}
		
		if (isset($this->request->post['lack_status'])) {
			$data['lack_status'] = $this->request->post['lack_status'];
		} elseif (!empty($product_info)) {
			$data['lack_status'] = $product_info['lack_status'];
		} else {
			$data['lack_status'] = 1;
		}

		if (isset($this->request->post['product_class1'])) {
			$data['product_class1'] = $this->request->post['product_class1'];
		} elseif (!empty($product_info)) {
			$data['product_class1'] = $product_info['product_class1'];
		} else {
			$data['product_class1'] = '';
		}

		if (isset($this->request->post['product_class2'])) {
			$data['product_class2'] = $this->request->post['product_class2'];
		} elseif (!empty($product_info)) {
			$data['product_class2'] = $product_info['product_class2'];
		} else {
			$data['product_class2'] = '';
		}

		if (isset($this->request->post['product_class3'])) {
			$data['product_class3'] = $this->request->post['product_class3'];
		} elseif (!empty($product_info)) {
			$data['product_class3'] = $product_info['product_class3'];
		} else {
			$data['product_class3'] = '';
		}

		if (isset($this->request->post['product_code'])) {
			$data['product_code'] = $this->request->post['product_code'];
		} elseif (!empty($product_info)) {
			$data['product_code'] = $product_info['product_code'];
		} else {
			$data['product_code'] = '';
		}

		//是否新品
		if (isset($this->request->post['newpro'])) {
			$data['newpro'] = $this->request->post['newpro'];
		} elseif (!empty($product_info)) {
			$data['newpro'] = $product_info['newpro'];
		} else {
			$data['newpro'] = 0;
		}
		
		//是否推荐
		if (isset($this->request->post['recommend'])) {
			$data['recommend'] = $this->request->post['recommend'];
		} elseif (!empty($product_info)) {
			$data['recommend'] = $product_info['recommend'];
		} else {
			$data['recommend'] = 0;
		}

		//是否清仓
		if (isset($this->request->post['clearance'])) {
			$data['clearance'] = $this->request->post['clearance'];
		} elseif (!empty($product_info)) {
			$data['clearance'] = $product_info['clearance'];
		} else {
			$data['clearance'] = 0;
		}

		//是否促销
		if (isset($this->request->post['promotion'])) {
			$data['promotion'] = $this->request->post['promotion'];
		} elseif (!empty($product_info)) {
			$data['promotion'] = $product_info['promotion'];
		} else {
			$data['promotion'] = 0;
		}
		
		//显示新品图标
		if (isset($this->request->post['show_new'])) {
			$data['show_new'] = $this->request->post['show_new'];
		} elseif (!empty($product_info)) {
			$data['show_new'] = $product_info['show_new'];
		} else {
			$data['show_new'] = 1;
		}
		//显示清仓图标
		if (isset($this->request->post['show_clearance'])) {
			$data['show_clearance'] = $this->request->post['show_clearance'];
		} elseif (!empty($product_info)) {
			$data['show_clearance'] = $product_info['show_clearance'];
		} else {
			$data['show_clearance'] = 0;
		}

		//显示备货中
		if (isset($this->request->post['show_stock'])) {
			$data['show_stock'] = $this->request->post['show_stock'];
		} elseif (!empty($product_info)) {
			$data['show_stock'] = $product_info['show_stock'];
		} else {
			$data['show_stock'] = 1;
		}

		if (isset($this->request->post['p_type'])) {
			$data['p_type'] = $this->request->post['p_type'];
		} elseif (!empty($product_info)) {
			$data['p_type'] = $product_info['p_type'];
		} else {
			$data['p_type'] = "";
		}

		if (isset($this->request->post['sku'])) {
			$data['sku'] = $this->request->post['sku'];
		} elseif (!empty($product_info)) {
			$data['sku'] = $product_info['sku'];
		} else {
			$data['sku'] = '';
		}

		if (isset($this->request->post['middle_package'])) {
			$data['middle_package'] = $this->request->post['middle_package'];
		} elseif (!empty($product_info)) {
			$data['middle_package'] = $product_info['middle_package'];
		} else {
			$data['middle_package'] = 0;
		}

		if (isset($this->request->post['upc'])) {
			$data['upc'] = $this->request->post['upc'];
		} elseif (!empty($product_info)) {
			$data['upc'] = $product_info['upc'];
		} else {
			$data['upc'] = '';
		}

		if (isset($this->request->post['ean'])) {
			$data['ean'] = $this->request->post['ean'];
		} elseif (!empty($product_info)) {
			$data['ean'] = $product_info['ean'];
		} else {
			$data['ean'] = '';
		}

		if (isset($this->request->post['item_no'])) {
			$data['item_no'] = $this->request->post['item_no'];
		} elseif (!empty($product_info)) {
			$data['item_no'] = $product_info['item_no'];
		} else {
			$data['item_no'] = '';
		}

		if (isset($this->request->post['packing_no'])) {
			$data['packing_no'] = $this->request->post['packing_no'];
		} elseif (!empty($product_info)) {
			$data['packing_no'] = $product_info['packing_no'];
		} else {
			$data['packing_no'] = '0';
		}

		if (isset($this->request->post['min_purchase_no'])) {
			$data['min_purchase_no'] = $this->request->post['min_purchase_no'];
		} elseif (!empty($product_info)) {
			$data['min_purchase_no'] = $product_info['min_purchase_no'];
		} else {
			$data['min_purchase_no'] = '0';
		}

		if (isset($this->request->post['jan'])) {
			$data['jan'] = $this->request->post['jan'];
		} elseif (!empty($product_info)) {
			$data['jan'] = $product_info['jan'];
		} else {
			$data['jan'] = '';
		}

		if (isset($this->request->post['isbn'])) {
			$data['isbn'] = $this->request->post['isbn'];
		} elseif (!empty($product_info)) {
			$data['isbn'] = $product_info['isbn'];
		} else {
			$data['isbn'] = '';
		}

		if (isset($this->request->post['mpn'])) {
			$data['mpn'] = $this->request->post['mpn'];
		} elseif (!empty($product_info)) {
			$data['mpn'] = $product_info['mpn'];
		} else {
			$data['mpn'] = '';
		}

		if (isset($this->request->post['location'])) {
			$data['location'] = $this->request->post['location'];
		} elseif (!empty($product_info)) {
			$data['location'] = $product_info['location'];
		} else {
			$data['location'] = '';
		}

		if (isset($this->request->post['gift_status'])) {
			$data['gift_status'] = $this->request->post['gift_status'];
		} elseif (!empty($product_info)) {
			$data['gift_status'] = $product_info['gift_status'];
		} else {
			$data['gift_status'] = 0;
		}

        /* @author sonicsjh*/
        $productTypeList = array(
            '1' => $this->language->get('t1_simple_product'),
            '2' => $this->language->get('t2_group_product'),
        );
        $data['productTypeList']  = $productTypeList;
        $data['product_type'] = 1;
        if (isset($this->request->post['product_type'])) {
            $data['product_type'] = $this->request->post['product_type'];
        }elseif (!empty($product_info)) {
            $data['product_type'] = $product_info['product_type'];
        }
        if (!array_key_exists($data['product_type'], $productTypeList))
            $data['product_type'] = 1;
        $data['error_filter_empty'] = $this->language->get('error_filter_empty');
        $data['product_id'] = $product_info['product_id'];

        $data['product_group'] = array();
        if (isset($this->request->post['groupChild'])) {
            $data['product_group'] = $this->_initChildProducts($this->model_catalog_mvd_product->getChildProductsInGroup($this->request->post['groupChild']));
        }elseif (!empty($product_info)) {
            $data['product_group'] = $this->_initChildProducts($this->model_catalog_mvd_product->getChildProductsInGroup($product_info['groupChild']));
        }

        // var_dump($product_info['groupChild']);
        // var_dump($this->request->post['groupChild']);
        /* @author sonicsjh*/
		//mvds
		if (isset($this->request->get['product_id'])) {
			foreach ($this->model_catalog_mvd_product->getProductDescriptions($this->request->get['product_id']) as $pdname) {
				$product_name = $pdname['name'];
			}
		}
			
		if (isset($this->request->post['product_name'])) {
			$data['product_name'] = $this->request->post['product_name'];
		} elseif (!empty($product_name)) {
			$data['product_name'] = $product_name;
		} else {
			$data['product_name'] = '';
		}
		
		$this->load->model('setting/setting');
		$data['config'] = $this->model_setting_setting->getSetting('config');
		$data['countries'] = $this->model_catalog_mvd_product->getCountry();	
			
		if (isset($this->request->post['ori_country'])) {
			$data['ori_country'] = $this->request->post['ori_country'];
		} else if (isset($product_info)) {
			$data['ori_country'] = $product_info['ori_country'];
		} else {
			$data['ori_country'] = '';
		}
			
		if (isset($this->request->post['product_cost'])) {
			$data['product_cost'] = $this->request->post['product_cost'];
		} else if (isset($product_info)) {
			$data['product_cost'] = $product_info['product_cost'];
		} else {
			$data['product_cost'] = '';
		}
			
		$data['couriers'] = $this->model_catalog_mvd_product->getCourier();
		
		if (isset($this->request->post['shipping_method'])) {
			$data['shipping_method'] = $this->request->post['shipping_method'];
		} else if (isset($product_info)) {
			$data['shipping_method'] = $product_info['shipping_method'];
		} else {
			$data['shipping_method'] = '0';
		}
			
		if (isset($this->request->post['prefered_shipping'])) {
			$data['prefered_shipping'] = $this->request->post['prefered_shipping'];
		} else if (isset($product_info)) {
			$data['prefered_shipping'] = $product_info['prefered_shipping'];
		} else {
			$data['prefered_shipping'] = '0';
		}
			
		if (isset($this->request->post['shipping_cost'])) {
			$data['shipping_cost'] = $this->request->post['shipping_cost'];
		} else if (isset($product_info)) {
			$data['shipping_cost'] = $product_info['shipping_cost'];
		} else {
			$data['shipping_cost'] = '';
		}
			
		if (isset($this->request->post['vtotal'])) {
			$data['vtotal'] = $this->request->post['vtotal'];
		} else if (isset($product_info)) {
			$data['vtotal'] = $product_info['vtotal'];
		} else {
			$data['vtotal'] = '';
		}
			
		if (isset($this->request->post['product_url'])) {
			$data['product_url'] = $this->request->post['product_url'];
		} else if (isset($product_info)) {
			$data['product_url'] = $product_info['product_url'];
		} else {
			$data['product_url'] = '';
		}
			
		$data['vendors'] = $this->model_catalog_mvd_product->getVendors();
		
		if (isset($this->request->post['vendor'])) {
			$data['vendor'] = $this->request->post['vendor'];
		} elseif (isset($product_info)) {
			$data['vendor'] = $product_info['vendor'];
		} else {
			$data['vendor'] = 0;
		}
					
		if (isset($this->request->post['wholesale'])) {
			$data['wholesale'] = $this->request->post['wholesale'];
		} else if (isset($product_info)) {
			$data['wholesale'] = $product_info['wholesale'];
		} else {
			$data['wholesale'] = '';
		}
			
		if (isset($this->request->post['company'])) {
			$data['company'] = $this->request->post['company'];
		} else if (isset($product_info)) {
			$data['company'] = $product_info['company'];
		} else {
			$data['company'] = '';
		}
			
		if (isset($this->request->post['vname'])) {
			$data['vname'] = $this->request->post['vname'];
		} else if (isset($product_info)) {
			$data['vname'] = $product_info['vname'];
		} else {
			$data['vname'] = '';
		}
			
		if (isset($this->request->post['telephone'])) {
			$data['telephone'] = $this->request->post['telephone'];
		} else if (isset($product_info)) {
			$data['telephone'] = $product_info['telephone'];
		} else {
			$data['telephone'] = '';
		}
			
		if (isset($this->request->post['fax'])) {
			$data['fax'] = $this->request->post['fax'];
		} else if (isset($product_info)) {
			$data['fax'] = $product_info['fax'];
		} else {
			$data['fax'] = '';
		}
			
		if (isset($this->request->post['email'])) {
			$data['email'] = $this->request->post['email'];
		} else if (isset($product_info)) {
			$data['email'] = $product_info['email'];
		} else {
			$data['email'] = '';
		}
			
		if (isset($this->request->post['paypal_email'])) {
			$data['paypal_email'] = $this->request->post['paypal_email'];
		} else if (isset($product_info)) {
			$data['paypal_email'] = $product_info['paypal_email'];
		} else {
			$data['paypal_email'] = '';
		}
			
		if (isset($this->request->post['vendor_description'])) {
			$data['vendor_description'] = $this->request->post['vendor_description'];
		} else if (isset($product_info)) {
			$data['vendor_description'] = $product_info['vendor_description'];
		} else {
			$data['vendor_description'] = '';
		}
					
		if (isset($this->request->post['vendor_address'])) {
			$data['vendor_address'] = $this->request->post['vendor_address'];
		} else if (isset($product_info)) {
			$data['vendor_address'] = $product_info['address'];
		} else {
			$data['vendor_address'] = '';
		}
			
			
		if (isset($this->request->post['vendor_country_zone'])) {
			$data['vendor_country_zone'] = $this->request->post['vendor_country_zone'];
		} else if (isset($product_info)) {
			if (isset($product_info['country_id']) && isset($product_info['zone_id'])) {
				$this->load->model('localisation/zone');
				$zone = $this->model_localisation_zone->getZone((int)$product_info['zone_id']);
				if ($zone) {
					$vendor_zone = $zone['name'];
				} else {
					$vendor_zone =  $this->language->get('text_none');
				}
				
				$this->load->model('localisation/country');
				$country = $this->model_localisation_country->getCountry((int)$product_info['country_id']);
				$vendor_country = $country['name'];
			} else {
				$vendor_zone = '';
				$vendor_country = '';
			}
			$data['vendor_country_zone'] = $vendor_country . ', ' . $vendor_zone;
		} else {
			$data['vendor_country_zone'] = '';
		}
			
		if (isset($this->request->post['store_url'])) {
			$data['store_url'] = $this->request->post['store_url'];
		} else if (isset($product_info)) {
			$data['store_url'] = $product_info['store_url'];
		} else {
			$data['store_url'] = '';
		}
			
		$this->load->model('localisation/geo_zone');
		$data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();
			
		if (isset($this->request->post['product_shipping'])) {
			$data['product_shippings'] = $this->request->post['product_shipping'];
		} elseif (isset($this->request->get['product_id'])) {
			$data['product_shippings'] = $this->model_catalog_mvd_product->getProductShippings($this->request->get['product_id']);
		} else {
			$data['product_shippings'] = array();
		}
		//mvde

		$this->load->model('setting/store');

		$data['stores'] = $this->model_setting_store->getStores();

		if (isset($this->request->post['product_store'])) {
			$data['product_store'] = $this->request->post['product_store'];
		} elseif (isset($this->request->get['product_id'])) {
			$data['product_store'] = $this->model_catalog_mvd_product->getProductStores($this->request->get['product_id']);
		} else {
			$data['product_store'] = array(0);
		}

		if (isset($this->request->post['keyword'])) {
			$data['keyword'] = $this->request->post['keyword'];
		} elseif (!empty($product_info)) {
			$data['keyword'] = $product_info['keyword'];
		} else {
			$data['keyword'] = '';
		}

		if (isset($this->request->post['shipping'])) {
			$data['shipping'] = $this->request->post['shipping'];
		} elseif (!empty($product_info)) {
			$data['shipping'] = $product_info['shipping'];
		} else {
			$data['shipping'] = 1;
		}

		if (isset($this->request->post['price'])) {
			$data['price'] = $this->request->post['price'];
		} elseif (!empty($product_info)) {
			$data['price'] = $product_info['price'];
		} else {
			$data['price'] = '';
		}

		if (isset($this->request->post['sale_price'])) {
			$data['sale_price'] = $this->request->post['sale_price'];
		} elseif (!empty($product_info)) {
			$data['sale_price'] = $product_info['sale_price'];
		} else {
			$data['sale_price'] = '';
		}

		$this->load->model('catalog/recurring');

		$data['recurrings'] = $this->model_catalog_recurring->getRecurrings();

		if (isset($this->request->post['product_recurrings'])) {
			$data['product_recurrings'] = $this->request->post['product_recurrings'];
		} elseif (!empty($product_info)) {
			$data['product_recurrings'] = $this->model_catalog_mvd_product->getRecurrings($product_info['product_id']);
		} else {
			$data['product_recurrings'] = array();
		}

		$this->load->model('localisation/tax_class');

		$data['tax_classes'] = $this->model_localisation_tax_class->getTaxClasses();

		if (isset($this->request->post['tax_class_id'])) {
			$data['tax_class_id'] = $this->request->post['tax_class_id'];
		} elseif (!empty($product_info)) {
			$data['tax_class_id'] = $product_info['tax_class_id'];
		} else {
			$data['tax_class_id'] = 0;
		}

		if (isset($this->request->post['date_available'])) {
			$data['date_available'] = $this->request->post['date_available'];
		} elseif (!empty($product_info)) {
			$data['date_available'] = ($product_info['date_available'] != '0000-00-00') ? $product_info['date_available'] : '';
		} else {
			$data['date_available'] = date('Y-m-d');
		}

		if (isset($this->request->post['quantity'])) {
			$data['quantity'] = $this->request->post['quantity'];
		} elseif (!empty($product_info)) {
			$data['quantity'] = $product_info['quantity'];
		} else {
			$data['quantity'] = 1;
		}

		if (isset($this->request->post['minimum'])) {
			$data['minimum'] = $this->request->post['minimum'];
		} elseif (!empty($product_info)) {
			$data['minimum'] = $product_info['minimum'];
		} else {
			$data['minimum'] = 1;
		}

		if (isset($this->request->post['addnum'])) {
			$data['addnum'] = $this->request->post['addnum'];
		} elseif (!empty($product_info)) {
			$data['addnum'] = $product_info['addnum'];
		} else {
			$data['addnum'] = 1;
		}

		if (isset($this->request->post['subtract'])) {
			$data['subtract'] = $this->request->post['subtract'];
		} elseif (!empty($product_info)) {
			$data['subtract'] = $product_info['subtract'];
		} else {
			$data['subtract'] = 1;
		}

		if (isset($this->request->post['sort_order'])) {
			$data['sort_order'] = $this->request->post['sort_order'];
		} elseif (!empty($product_info)) {
			//$data['sort_order'] = $product_info['sort_order'];
			//mvds
			$data['sort_order'] = $product_info['psort_order'];
			//mvde
		} else {
			$data['sort_order'] = 1;
		}

		$this->load->model('localisation/stock_status');

		$data['stock_statuses'] = $this->model_localisation_stock_status->getStockStatuses();

		if (isset($this->request->post['stock_status_id'])) {
			$data['stock_status_id'] = $this->request->post['stock_status_id'];
		} elseif (!empty($product_info)) {
			$data['stock_status_id'] = $product_info['stock_status_id'];
		} else {
			$data['stock_status_id'] = 0;
		}

		if (isset($this->request->post['status'])) {
			$data['status'] = $this->request->post['status'];
		} elseif (!empty($product_info)) {
			$data['status'] = $product_info['status'];
		} else {
			$data['status'] = 3;
		}

		if (isset($this->request->post['weight'])) {
			$data['weight'] = $this->request->post['weight'];
		} elseif (!empty($product_info)) {
			$data['weight'] = $product_info['weight'];
		} else {
			$data['weight'] = '';
		}

		$this->load->model('localisation/weight_class');

		$data['weight_classes'] = $this->model_localisation_weight_class->getWeightClasses();

		if (isset($this->request->post['weight_class_id'])) {
			$data['weight_class_id'] = $this->request->post['weight_class_id'];
		} elseif (!empty($product_info)) {
			$data['weight_class_id'] = $product_info['weight_class_id'];
		} else {
			$data['weight_class_id'] = $this->config->get('config_weight_class_id');
		}

		if (isset($this->request->post['length'])) {
			$data['length'] = $this->request->post['length'];
		} elseif (!empty($product_info)) {
			$data['length'] = $product_info['length'];
		} else {
			$data['length'] = '';
		}

		if (isset($this->request->post['width'])) {
			$data['width'] = $this->request->post['width'];
		} elseif (!empty($product_info)) {
			$data['width'] = $product_info['width'];
		} else {
			$data['width'] = '';
		}

		if (isset($this->request->post['height'])) {
			$data['height'] = $this->request->post['height'];
		} elseif (!empty($product_info)) {
			$data['height'] = $product_info['height'];
		} else {
			$data['height'] = '';
		}

		$this->load->model('localisation/length_class');

		$data['length_classes'] = $this->model_localisation_length_class->getLengthClasses();

		if (isset($this->request->post['length_class_id'])) {
			$data['length_class_id'] = $this->request->post['length_class_id'];
		} elseif (!empty($product_info)) {
			$data['length_class_id'] = $product_info['length_class_id'];
		} else {
			$data['length_class_id'] = $this->config->get('config_length_class_id');
		}

		$this->load->model('catalog/manufacturer');

		if (isset($this->request->post['manufacturer_id'])) {
			$data['manufacturer_id'] = $this->request->post['manufacturer_id'];
		} elseif (!empty($product_info)) {
			$data['manufacturer_id'] = $product_info['manufacturer_id'];
		} else {
			$data['manufacturer_id'] = 0;
		}

		if (isset($this->request->post['manufacturer'])) {
			$data['manufacturer'] = $this->request->post['manufacturer'];
		} elseif (!empty($product_info)) {
			$manufacturer_info = $this->model_catalog_manufacturer->getManufacturer($product_info['manufacturer_id']);

			if ($manufacturer_info) {
				$data['manufacturer'] = $manufacturer_info['name'];
			} else {
				$data['manufacturer'] = '';
			}
		} else {
			$data['manufacturer'] = '';
		}

		// Categories
		$this->load->model('catalog/category');

		if (isset($this->request->post['product_category'])) {
			$categories = $this->request->post['product_category'];
		} elseif (isset($this->request->get['product_id'])) {
			$categories = $this->model_catalog_mvd_product->getProductCategories($this->request->get['product_id']);
		} else {
			$categories = array();
		}

		$data['product_categories'] = array();

		foreach ($categories as $category_id) {
			$category_info = $this->model_catalog_category->getCategory($category_id);

			if ($category_info) {
				$data['product_categories'][] = array(
					'category_id' => $category_info['category_id'],
					'name' => ($category_info['path']) ? $category_info['path'] . ' &gt; ' . $category_info['code']." ".$category_info['name'] : $category_info['code']." ".$category_info['name']
				);
			}
		}

		// Filters
		$this->load->model('catalog/filter');

		if (isset($this->request->post['product_filter'])) {
			$filters = $this->request->post['product_filter'];
		} elseif (isset($this->request->get['product_id'])) {
			$filters = $this->model_catalog_mvd_product->getProductFilters($this->request->get['product_id']);
		} else {
			$filters = array();
		}

		$data['product_filters'] = array();

		foreach ($filters as $filter_id) {
			$filter_info = $this->model_catalog_filter->getFilter($filter_id);

			if ($filter_info) {
				$data['product_filters'][] = array(
					'filter_id' => $filter_info['filter_id'],
					'name'      => $filter_info['group'] . ' &gt; ' . $filter_info['name']
				);
			}
		}

		// Attributes
		$this->load->model('catalog/attribute');

		if (isset($this->request->post['product_attribute'])) {
			$product_attributes = $this->request->post['product_attribute'];
		} elseif (isset($this->request->get['product_id'])) {
			$product_attributes = $this->model_catalog_mvd_product->getProductAttributes($this->request->get['product_id']);
		} else {
			$product_attributes = array();
		}

		$data['product_attributes'] = array();

		foreach ($product_attributes as $product_attribute) {
			$attribute_info = $this->model_catalog_attribute->getAttribute($product_attribute['attribute_id']);

			if ($attribute_info) {
				$data['product_attributes'][] = array(
					'attribute_id'                  => $product_attribute['attribute_id'],
					'name'                          => $attribute_info['name'],
					'product_attribute_description' => $product_attribute['product_attribute_description']
				);
			}
		}

		// Options
		$this->load->model('catalog/option');

		if (isset($this->request->post['product_option'])) {
			$product_options = $this->request->post['product_option'];
		} elseif (isset($this->request->get['product_id'])) {
			$product_options = $this->model_catalog_mvd_product->getProductOptions($this->request->get['product_id']);
		} else {
			$product_options = array();
		}


		$data['product_options'] = array();

        $this->load->model('stock/stocksearch');

		foreach ($product_options as $product_option) {
			$product_option_value_data = array();
			
			if (isset($product_option['product_option_value'])) {
				foreach ($product_option['product_option_value'] as $product_option_value) {
                    $productStock = $this->model_stock_stocksearch->getGatherQtyByProductCode($product_option_value['product_code']);
					$product_option_value_data[] = array(
						'product_option_value_id' => $product_option_value['product_option_value_id'],
						'option_value_id'         => $product_option_value['option_value_id'],
						'product_code'            => $product_option_value['product_code'],
						'quantity'                => $product_option_value['quantity'],
						'subtract'                => $product_option_value['subtract'],
						'price'                   => $product_option_value['price'],
						'price_prefix'            => $product_option_value['price_prefix'],
						'points'                  => $product_option_value['points'],
						'points_prefix'           => $product_option_value['points_prefix'],
						'weight'                  => $product_option_value['weight'],
						'weight_prefix'           => $product_option_value['weight_prefix'],
                        'availableQty'            => $productStock['availableQty']
					);
				}
			}

			$data['product_options'][] = array(
				'product_option_id'    => $product_option['product_option_id'],
				'product_option_value' => $product_option_value_data,
				'option_id'            => $product_option['option_id'],
				'name'                 => $product_option['name'],
				'type'                 => $product_option['type'],
				'value'                => isset($product_option['value']) ? $product_option['value'] : '',
				'required'             => $product_option['required']
			);
		}

		$data['option_values'] = array();

		foreach ($data['product_options'] as $product_option) {
			if ($product_option['type'] == 'select' || $product_option['type'] == 'radio' || $product_option['type'] == 'checkbox' || $product_option['type'] == 'image') {
				if (!isset($data['option_values'][$product_option['option_id']])) {
					$data['option_values'][$product_option['option_id']] = $this->model_catalog_option->getOptionValues($product_option['option_id']);
				}
			}
		}

		$this->load->model('customer/customer_group');

		$data['customer_groups'] = $this->model_customer_customer_group->getCustomerGroups();

		if (isset($this->request->post['product_discount'])) {
			$product_discounts = $this->request->post['product_discount'];
		} elseif (isset($this->request->get['product_id'])) {
			$product_discounts = $this->model_catalog_mvd_product->getProductDiscounts($this->request->get['product_id']);
		} else {
			$product_discounts = array();
		}

		$data['product_discounts'] = array();

		foreach ($product_discounts as $product_discount) {
			$data['product_discounts'][] = array(
				'customer_group_id' => $product_discount['customer_group_id'],
				'quantity'          => $product_discount['quantity'],
				'priority'          => $product_discount['priority'],
				'price'             => $product_discount['price'],
				'date_start'        => ($product_discount['date_start'] != '0000-00-00') ? $product_discount['date_start'] : '',
				'date_end'          => ($product_discount['date_end'] != '0000-00-00') ? $product_discount['date_end'] : ''
			);
		}

		if (isset($this->request->post['product_special'])) {
			$product_specials = $this->request->post['product_special'];
		} elseif (isset($this->request->get['product_id'])) {
			$product_specials = $this->model_catalog_mvd_product->getProductSpecials($this->request->get['product_id']);
		} else {
			$product_specials = array();
		}

		$data['product_specials'] = array();

		foreach ($product_specials as $product_special) {
			$data['product_specials'][] = array(
				'product_special_id' => $product_special['product_special_id'],
				'customer_group_id' => $product_special['customer_group_id'],
				'priority'          => $product_special['priority'],
				'price'             => $product_special['price'],
				'date_start'        => ($product_special['date_start'] != '0000-00-00') ? $product_special['date_start'] : '',
				'date_end'          => ($product_special['date_end'] != '0000-00-00') ? $product_special['date_end'] :  ''
			);
		}

		// Images
		if (isset($this->request->post['product_image'])) {
			$product_images = $this->request->post['product_image'];
		} elseif (isset($this->request->get['product_id'])) {
			$product_images = $this->model_catalog_mvd_product->getProductImages($this->request->get['product_id']);
		} else {
			$product_images = array();
		}

		$data['product_images'] = array();
		foreach ($product_images as $product_image) {
			if (is_file(DIR_IMAGE . $product_image['image'])) {
				$image = $product_image['image'];
				$thumb = $product_image['image'];
			} else {
				$image = '';
				$thumb = 'no_image.png';
			}
			

			$data['product_images'][] = array(
				'image'      => $image,
				'thumb'      => $this->model_tool_image->resize($thumb, 100, 100),
				'sort_order' => $product_image['sort_order']
			);
		}

		// Downloads
		$this->load->model('catalog/download');

		if (isset($this->request->post['product_download'])) {
			$product_downloads = $this->request->post['product_download'];
		} elseif (isset($this->request->get['product_id'])) {
			$product_downloads = $this->model_catalog_mvd_product->getProductDownloads($this->request->get['product_id']);
		} else {
			$product_downloads = array();
		}

		$data['product_downloads'] = array();

		foreach ($product_downloads as $download_id) {
			$download_info = $this->model_catalog_download->getDownload($download_id);

			if ($download_info) {
				$data['product_downloads'][] = array(
					'download_id' => $download_info['download_id'],
					'name'        => $download_info['name']
				);
			}
		}

		if (isset($this->request->post['product_related'])) {
			$products = $this->request->post['product_related'];
		} elseif (isset($this->request->get['product_id'])) {
			$products = $this->model_catalog_mvd_product->getProductRelated($this->request->get['product_id']);
		} else {
			$products = array();
		}

		$data['product_relateds'] = array();

		foreach ($products as $product_id) {
			$related_info = $this->model_catalog_mvd_product->getProduct($product_id);

			if ($related_info) {
				$data['product_relateds'][] = array(
					'product_id' => $related_info['product_id'],
					'name'       => $related_info['name']
				);
			}
		}

		if (isset($this->request->post['points'])) {
			$data['points'] = $this->request->post['points'];
		} elseif (!empty($product_info)) {
			$data['points'] = $product_info['points'];
		} else {
			$data['points'] = '';
		}

		if (isset($this->request->post['product_reward'])) {
			$data['product_reward'] = $this->request->post['product_reward'];
		} elseif (isset($this->request->get['product_id'])) {
			$data['product_reward'] = $this->model_catalog_mvd_product->getProductRewards($this->request->get['product_id']);
		} else {
			$data['product_reward'] = array();
		}

		if (isset($this->request->post['product_layout'])) {
			$data['product_layout'] = $this->request->post['product_layout'];
		} elseif (isset($this->request->get['product_id'])) {
			$data['product_layout'] = $this->model_catalog_mvd_product->getProductLayouts($this->request->get['product_id']);
		} else {
			$data['product_layout'] = array();
		}

		$this->load->model('design/layout');

		$data['layouts'] = $this->model_design_layout->getLayouts();
		$data['histories'] = $this->model_catalog_mvd_product->getProHistory($this->request->get['product_id']);
		$data['safe_quantity'] = $this->model_catalog_mvd_product->getInventory($this->request->get['product_id']);
		// var_dump($data['safe_quantity']);
		// var_dump($data['product_specials']);
		// $data['avbuy'] = $this->model_catalog_mvd_product->getAgvBuyByid($this->request->get['product_id']);
		if (empty($data['avbuy'])) {
			$data['avbuy'] = $data['product_cost'];
		}
		$special = $data['sale_price'];
		$specialml = $data['sale_price'];

		$product_specials = $this->model_catalog_mvd_product->getProductSpecials($this->request->get['product_id']);

		foreach ($product_specials  as $product_special) {
			if (($product_special['date_start'] == '0000-00-00' || strtotime($product_special['date_start']) < time()) && ($product_special['date_end'] == '0000-00-00' || strtotime($product_special['date_end']) > time())) {
			
				$special = $product_special['price'];
				if ($product_special['customer_group_id']==1) {
					$specialml = $product_special['price'];
					
				}

				break;
			}
		}
		// var_dump($special);
		// var_dump($data['avbuy']);
		$data['ml'] = round(($specialml-$data['avbuy'])/$special*100,2).'%';
		/*分配区域*/
		$this->load->model('area/area');

		$data['only_countries'] = $this->model_area_area->getOnlyCountries($this->request->get['product_id']);
		$data['only_zones'] = $this->model_area_area->getOnlyZones($this->request->get['product_id']);
		$data['no_countries'] = $this->model_area_area->getNoCountries($this->request->get['product_id']);
		$data['no_zones'] = $this->model_area_area->getNoZones($this->request->get['product_id']);
		/*分配区域*/

		$data['header'] = $this->load->controller('common/header');
		$data['column_left'] = $this->load->controller('common/column_left');
		$data['footer'] = $this->load->controller('common/footer');
		$data['user_group_id'] = $this->model_catalog_mvd_product->userGroup($this->user->getId());
		$this->response->setOutput($this->load->view('catalog/mvd_product_form.tpl', $data));
	}

	protected function validateForm() {
		if (!$this->user->hasPermission('modify', 'catalog/mvd_product')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		foreach ($this->request->post['product_description'] as $language_id => $value) {
			if ((utf8_strlen($value['name']) < 3) || (utf8_strlen($value['name']) > 255)) {
				$this->error['name'][$language_id] = $this->language->get('error_name');
			}

			if ((utf8_strlen($value['meta_title']) < 3) || (utf8_strlen($value['meta_title']) > 255)) {
				$this->error['meta_title'][$language_id] = $this->language->get('error_meta_title');
			}
		}
			
		/*商品编码必须唯一性*/
		$code_info = $this->model_catalog_mvd_product->getProductByCode($this->request->post['product_code'],$this->request->get['product_id']);
		if($code_info){
			$this->error['product_code'] = $this->language->get('error_product_code_ uniqueness');
		}
		/*商品编码必须唯一性*/

		/*商品编码必须为10位*/
		if ((utf8_strlen($this->request->post['product_code'])) != 10) {
			$this->error['product_code'] = $this->language->get('error_product_code');
		}
		/*商品编码必须为10位*/

		if ((utf8_strlen($this->request->post['model']) < 1) || (utf8_strlen($this->request->post['model']) > 64)) {
			$this->error['model'] = $this->language->get('error_model');
		}
		
		if (utf8_strlen($this->request->post['keyword']) > 0) {
			$this->load->model('catalog/url_alias');

			$url_alias_info = $this->model_catalog_url_alias->getUrlAlias($this->request->post['keyword']);

			if ($url_alias_info && isset($this->request->get['product_id']) && $url_alias_info['query'] != 'product_id=' . $this->request->get['product_id']) {
				$this->error['keyword'] = sprintf($this->language->get('error_keyword'));
			}

			if ($url_alias_info && !isset($this->request->get['product_id'])) {
				$this->error['keyword'] = sprintf($this->language->get('error_keyword'));
			}
		}

		if ($this->request->post['vendor'] == 0){
			$this->error['vendor'] = '请选择供应商';
		}

		if (!isset($this->request->post['product_option'][0]['product_option_value'])){
			$this->error['product_option'] = '请设置一个产品选项';
		}

		if (empty($this->request->post['price'])){
			$this->error['price'] = '请填写价格';
		}

		if (empty($this->request->post['sale_price'])){
			$this->error['sale_price'] = '请填写商品售价';
		}

		if (empty($this->request->post['product_cost']) || $this->request->post['product_cost']==0){
			$this->error['product_cost'] = '请填写商品成本';
		}

		$product_special = null;
		if(isset($this->request->post['product_special'])) {
			$product_special = $this->request->post['product_special'];	
		}
		// if (empty($product_special) || count($product_special)<1 || empty($product_special[0]['price'])) {
		// 	$this->error['product_special'] = '请填写价格';
		// }

		if (isset($this->request->post['product_option']) && count($this->request->post['product_option']) > 1){
			$this->error['product_option'] = '最多设置一个产品选项';
		}

		//如果商品product_option_value_id有被包含在某家logcenter，则不能删除
		if(isset($this->request->get['product_id'])) {
			$this->load->model('catalog/product');
			$to_save_opt_value_ids = array();
			if(isset($this->request->post['product_option']) && isset($this->request->post['product_option'][0]) && isset($this->request->post['product_option'][0]['product_option_value'])) {
				foreach ($this->request->post['product_option'][0]['product_option_value'] as $pov) {
					$to_save_opt_value_ids[] = $pov['product_option_value_id'];
				}	
			}
			$to_save_opt_value_ids = implode(',', $to_save_opt_value_ids);
			$to_del_product_option_value_ids = $this->model_catalog_product->getToDelProductOptionValueIds($this->request->get['product_id'], $to_save_opt_value_ids);
			if ($to_del_product_option_value_ids) {
				$to_del_ids = array();
				foreach ($to_del_product_option_value_ids as $tdpovi) {
					$to_del_ids[] = $tdpovi['product_option_value_id'];
				}
				$to_del_ids = implode(',', $to_del_ids);
				$errors = $this->model_catalog_product->checkLogOptInventory($to_del_ids);

				$error_msg = '';
				if (!empty($errors)) {
					$error_msg = '删除错误，因为产品选项与物流营销中心仍有绑定关系：';
					foreach ($errors as $errm) {
						$error_msg .= $errm['name'] . ' vs ' . $errm['logcenter_name'] . '; ';
					}
					$this->error['warning'] = $error_msg;
				}
			}
		}

		if ($this->error && !isset($this->error['warning'])) {
			$this->error['warning'] = $this->language->get('error_warning');
		}

		return !$this->error;
	}

	protected function validateDelete() {
		if (!$this->user->hasPermission('modify', 'catalog/mvd_product')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		//判断产品是否有关联在logcenter
		$this->load->model('catalog/lgi_product');
		$errors = $this->model_catalog_lgi_product->checkLogInventory(implode(',', $this->request->post['selected']));
		$error_msg = '';
		if (!empty($errors)) {
			$error_msg = '删除错误，因为产品与物流营销中心仍有绑定关系：';
			foreach ($errors as $errm) {
				$error_msg .= $errm['name'] . ' vs ' . $errm['logcenter_name'] . '; ';
			}
			$this->error['warning'] = $error_msg;
		}

		return !$this->error;
	}

	protected function validateCopy() {
		if (!$this->user->hasPermission('modify', 'catalog/mvd_product')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		return !$this->error;
	}
	
	//mvds
	public function vendor() {
		$this->load->model('catalog/mvd_product');
				
		if (isset($this->request->get['vendor_id'])) {
			$vendor_id = $this->request->get['vendor_id'];
		} else {
			$vendor_id = 0;
		}
		
		$results = $this->model_catalog_mvd_product->getVendorsByVendorId($vendor_id);
		
		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($results));
	}
			
	public function approve_notification($pname,$vendor_id) {
		$this->language->load('mail/email_notification');
		$this->load->model('catalog/mvd_product');
				
		$vendor_data = $this->model_catalog_mvd_product->getVendorData($vendor_id);
		$subject = sprintf($this->language->get('text_subject_approve'),$pname);
				
		$text = sprintf($this->language->get('text_to'), $vendor_data['firstname'] . ' ' . $vendor_data['lastname']) . "<br/><br/>";				
		$text .= sprintf($this->language->get('text_message_approve'), $pname) . "<br/><br/>";						
		$text .= $this->language->get('text_thanks') . "<br/>";
		$text .= $this->config->get('config_name') . "<br/><br/>";
		$text .= $this->language->get('text_system');
		
		$mail = new Mail();
		$mail->protocol = $this->config->get('config_mail_protocol');
		$mail->parameter = $this->config->get('config_mail_parameter');
		$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
		$mail->smtp_username = $this->config->get('config_mail_smtp_username');
		$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
		$mail->smtp_port = $this->config->get('config_mail_smtp_port');
		$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
									
		$mail->setTo($vendor_data['email']);
		$mail->setFrom($this->config->get('config_email'));
		$mail->setSender($this->config->get('config_name'));
		$mail->setSubject(html_entity_decode($subject, ENT_QUOTES, 'UTF-8'));
		$mail->setText(html_entity_decode($text, ENT_QUOTES, 'UTF-8'));
		$mail->setHtml(html_entity_decode($text, ENT_QUOTES, 'UTF-8'));
		$mail->send();
	}
	//mvde

	public function autocomplete() {
		$json = array();

		//if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model'])) {
		//mvds
		if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model']) || isset($this->request->get['filter_sku']) || isset($this->request->get['filter_product_code'])) {
		//mvde
			$this->load->model('catalog/mvd_product');
			$this->load->model('catalog/option');

			if (isset($this->request->get['filter_name'])) {
				$filter_name = $this->request->get['filter_name'];
			} else {
				$filter_name = '';
			}

			if (isset($this->request->get['filter_model'])) {
				$filter_model = $this->request->get['filter_model'];
			} else {
				$filter_model = '';
			}
			
			//商品编码
			if (isset($this->request->get['filter_product_code'])) {
				$filter_product_code = $this->request->get['filter_product_code'];
			} else {
				$filter_product_code = '';
			}
			
			//mvds
			if (isset($this->request->get['filter_sku'])) {
				$filter_sku = $this->request->get['filter_sku'];
			} else {
				$filter_sku = '';
			}
			//mvde

			if (isset($this->request->get['limit'])) {
				$limit = $this->request->get['limit'];
			} else {
				$limit = 5;
			}

			$filter_data = array(
				'filter_name'  => $filter_name,
				//商品编码
				'filter_product_code'   => $filter_product_code,
				//mvds
				'filter_sku'   => $filter_sku,
				//mvde
				'filter_model' => $filter_model,
				'start'        => 0,
				'limit'        => $limit
			);

			$results = $this->model_catalog_mvd_product->getProducts($filter_data);

			foreach ($results as $result) {
				$option_data = array();

				$product_options = $this->model_catalog_mvd_product->getProductOptions($result['product_id']);

				foreach ($product_options as $product_option) {
					$option_info = $this->model_catalog_option->getOption($product_option['option_id']);

					if ($option_info) {
						$product_option_value_data = array();

						foreach ($product_option['product_option_value'] as $product_option_value) {
							$option_value_info = $this->model_catalog_option->getOptionValue($product_option_value['option_value_id']);

							if ($option_value_info) {
								$product_option_value_data[] = array(
									'product_option_value_id' => $product_option_value['product_option_value_id'],
									'option_value_id'         => $product_option_value['option_value_id'],
									'name'                    => $option_value_info['name'],
									'price'                   => (float)$product_option_value['price'] ? $this->currency->format($product_option_value['price'], $this->config->get('config_currency')) : false,
									'price_prefix'            => $product_option_value['price_prefix']
								);
							}
						}

						$option_data[] = array(
							'product_option_id'    => $product_option['product_option_id'],
							'product_option_value' => $product_option_value_data,
							'option_id'            => $product_option['option_id'],
							'name'                 => $option_info['name'],
							'type'                 => $option_info['type'],
							'value'                => $product_option['value'],
							'required'             => $product_option['required']
						);
					}
				}

				$json[] = array(
					'product_id' => $result['product_id'],
					//mvds
					'sku'        => $result['sku'],
					'product_code'  => $result['product_code'],
					//mvde
					'name'       => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
					'model'      => $result['model'],
					'option'     => $option_data,
					'price'      => $result['price']
				);
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function stickSort(){
		$json['success'] = true;
		if(isset($this->request->get['product_id'])){
			$product_id = $this->request->get['product_id'];
			$this->load->model('catalog/mvd_product');
			$result = $this->model_catalog_mvd_product->stickSort($product_id);
			if($result){
				$json['info'] = '置顶成功';
			}else{
			$json['success'] = false;
			$json['info'] = '置顶失败';
			}
		}else{
			$json['success'] = false;
			$json['info'] = '置顶失败';
		}
		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

	public function exportlists(){
		$a =time();

		if (isset($this->request->get['filter_name'])) {
			$filter_name = $this->request->get['filter_name'];
			$filter_data['pd.name'] = array('like','%'.$filter_name.'%');
		} else {
			$filter_name = null;
		}

		if (isset($this->request->get['filter_model'])) {
			$filter_model = $this->request->get['filter_model'];
			$filter_data['p.model'] = array('like','%'.$filter_model.'%');
		} else {
			$filter_model = null;
		}

		if (isset($this->request->get['filter_price'])) {
			$filter_price = $this->request->get['filter_price'];
			$filter_data['p.price'] = $filter_price;
		} else {
			$filter_price = null;
		}

		if (isset($this->request->get['filter_quantity'])) {
			$filter_quantity = $this->request->get['filter_quantity'];
			$filter_data['p.quantity'] = trim($filter_quantity);
		} else {
			$filter_quantity = null;
		}

		if (isset($this->request->get['filter_status'])) {
			$filter_status = $this->request->get['filter_status'];
			$filter_data['p.status'] = $filter_status;
		} else {
			$filter_status = null;
		}
		
		//mvds
		if (isset($this->request->get['filter_sku'])) {
			$filter_sku = $this->request->get['filter_sku'];
			$filter_data['p.sku'] = array('like','%'.$filter_sku.'%');
		} else {
			$filter_sku = null;
		}
		
		//商品编码
		if (isset($this->request->get['filter_product_code'])) {
			$filter_product_code = $this->request->get['filter_product_code'];
			$filter_data['p.product_code'] = array('like','%'.$filter_product_code.'%');
		} else {
			$filter_product_code = null;
		}
			
		if (isset($this->request->get['filter_vendor'])) {
			$filter_vendor = $this->request->get['filter_vendor'];
		} else {
			$filter_vendor = NULL;
		}
			
		if (isset($this->request->get['filter_vendor_name'])) {
			$filter_vendor_name = $this->request->get['filter_vendor_name'];
			$filter_data['vs.vendor_id'] = $filter_vendor_name;
		} else {
			$filter_vendor_name = NULL;
		}
		$this->load->model('catalog/mvd_product');
		$allProduct_data = $this->model_catalog_mvd_product->getAllProductsDetail($filter_data);
		$status_array = array(
			'1' => '启用',
			'0'	=> '停用',
			'5' => '待审批',
			'3' => '初始',
			);
        $this->load->model('stock/stocksearch');
        $this->load->model('stock/warehouse');
        $this->load->model('sale/order');
        // echo time();
        $reportInfo = $this->model_sale_order->getGatherSaleReport($this->model_stock_stocksearch->getGatherQty());
        $BuyInfo = $this->model_stock_stocksearch->getGatherBuyQtyBy();
        //获取平均进货价
        // echo time();

        $Buyagvpric = $this->model_stock_stocksearch->getAgvBuy();
        // var_dump($Buyagvpric);die();
        // echo time();

        $BuyInfo = $this->model_stock_stocksearch->getGatherBuyQtyBy();
        $dcycle = $this->model_stock_stocksearch->getDeliveryCycleall();
        $saleqty = $this->model_stock_stocksearch->getAllsaleqty();
        // var_dump($saleqty);
        // echo time();

        $inventoryInfo = $this->model_stock_stocksearch->getGatherQtyV2();
        $warehouseList = $this->model_stock_warehouse->getAvailableWarehouse();
        $roInfo = $this->model_stock_stocksearch->getRo();
        // echo time();
        foreach ($allProduct_data as $key => $value) {

            if ($value['product_id'] < 1){//屏蔽 product_id=0 的脏数据
                continue;
            }
            $isSingle = (1 == $value['is_single'])? 'A' : 'B' ;
            
			
			/*判断是否存在于组合商品*/
			if($value['product_type'] == 1){
				$temp = $this->model_catalog_mvd_product->checkChild($value['product_id']);
				// $shelfName = $this->model_catalog_mvd_product->getShelf($value['product_id']);
				if (!empty($shelfName)) {
					if ($value['is_shelf_product']==0) {
						M('product')->where(array('product_id'=>$value['product_id']))->save(array('is_shelf_product'=>1));
					}
				}else{
					if ($value['is_shelf_product']==1) {
						M('product')->where(array('product_id'=>$value['product_id']))->save(array('is_shelf_product'=>0));
					}
				}

				//获取平均进货周期
				// $optime = $this->model_catalog_mvd_product->gettime($value['product_code']);

				
				if($temp == 1){
					$isChild = "是";
				}
				else if($temp == 0){
					$isChild = "否";
				}

			}
			else{
				$isChild = "我就是组合";
			}
			/*判断是否存在于组合商品*/
			
			$isStock = 0;
			foreach ($warehouseList as $warehouseInfo) {
                $temp = $inventoryInfo[$value['product_code']][$warehouseInfo['warehouse_id']]['availableQty'];
				if($temp > 0){
					$isStock = 1;
					break;
				}
            }

			/*判断是否备货中*/
			if($value['status'] == 3){
				$ready = "初始";
			}
			else if($value['status'] == 0){
				$ready = "停用";
			}
			else if($value['lack_status'] ==2){
				$ready = "暂时缺货";
			}
			else if($value['lack_status'] == 3){
				$ready = "永久缺货";
			}
			else if($value['clearance'] == 1){
				$ready = "清仓商品";
			}
			else if($value['quantity'] < $value['minimum'] || ($isStock == 0 && $value['product_type'] == 1&&$value['product_class1']!=852)){
				$ready = "备货中";
			}
			else{
				$ready = "有货";
			}

			// var_dump($value['lack_status']);die();
			if($value['lack_status'] ==2){
				$lack_status = "暂时缺货";
			}elseif($value['lack_status'] == 3){
				$lack_status = "永久缺货";
			}elseif($value['lack_status'] == 1){
				$lack_status = "正常";
			}
			
        	// var_dump($roInfo);die();

			$save_data[$key] = array(
				'product_id' 	=> $value['product_id'],	
				'maname' 	=> $value['maname'],	
				'lastname'		=> $value['lastname'],
				'vendor_name'	=> $value['vendor_name'],
				'product_code' => $value['product_code'],
				'mname'			=> $value['mname'],
				'name'          => $value['name'],
				'p_type' => $value['p_type'],
				'sku'			=> $value['sku'],
				'product_class1' =>$value['product_class1'],
				'product_class2' =>$value['product_class2'],
				'product_class3' =>$value['product_class3'],
				'model'			=> $value['model'],
				'packing_no'	=> $value['packing_no'],
				'middle_package'	=> $value['middle_package'],
				'minimum'		=> $value['minimum'],
				'product_cost'	=> $value['product_cost'],
				'price'			=> $value['price'],
				'sale_price'			=> $value['sale_price'],
				'date_added'	=> $value['date_added'],
				'status'		=> $status_array[$value['status']],
				'item_no'		=> $value['item_no'],
				'min_purchase_no'=>$value['min_purchase_no'],
				'quantity'		=> $value['quantity'],
				'length'		=> $value['length'],
				'height'		=> $value['height'],
				'width'			=> $value['width'],
				'weight'		=> $value['weight'],
				'sort_order'	=> $value['sort_order'],
				'ovd_name'      => $value['ovd_name'],
				'cd_name'		=> $value['cd_name'],
				'is_part'		=> $value['is_part'],
                'is_single'     => $isSingle,
                'shelfName'=>$shelfName,
                'optime'=>$optime,
                'is_shelf_product'=>$value['is_shelf_product']?'是':'否',
                'TQLW'          => $reportInfo[$value['product_code']]['TQLW'],
                'TP2017'          => $reportInfo[$value['product_code']]['TP2017'],
                'TQ2017'          => $reportInfo[$value['product_code']]['TQ2017'],
                'roInfo'          => $roInfo[$value['product_code']],
                'TPLW'          => $reportInfo[$value['product_code']]['TPLW'],
                'TQLM'          => $reportInfo[$value['product_code']]['TQLM'],
                'TPLM'          => $reportInfo[$value['product_code']]['TPLM'],
                'TQTY'          => $reportInfo[$value['product_code']]['TQTY'],
                'TPTY'          => $reportInfo[$value['product_code']]['TPTY'],
                'GPRTY'         => $reportInfo[$value['product_code']]['GPRTY'],
                'SQN'           => $reportInfo[$value['product_code']]['SQN'],
                'SCN'           => ($reportInfo[$value['product_code']]['SQN']*$value['product_cost']),
                'SSC'           => $reportInfo[$value['product_code']]['SSC'],
                'SIOW'          => $reportInfo[$value['product_code']]['SIOW'],
                'SIOWSC'        => $reportInfo[$value['product_code']]['SIOWSC'],
                'SAFE'        => $reportInfo[$value['product_code']]['SAFE'],
                'BUYQTY'        => $BuyInfo[$value['product_code']]['buyqty'],
                'BUYPRICE'        => $BuyInfo[$value['product_code']]['buyprice'],
                'AVC'        => $dcycle[$value['product_code']]['av'],
                'SALEQTY'        => $saleqty[$value['product_code']]['quantity'],
                'clearance'     => $value['clearance'],
                'Lack_status'     => $lack_status,
				'isChild' => $isChild,
				'ready' => $ready,
            );
            foreach ($warehouseList as $warehouseInfo) {
                $save_data[$key]['wh_'.$warehouseInfo['warehouse_id']] = $inventoryInfo[$value['product_code']][$warehouseInfo['warehouse_id']]['availableQty'];
            }

            //如果有平均进货价取平均，没有取进货价
			$product_cost = $Buyagvpric[$value['product_code']]['buyav'];
			$product_costn = floatval($value['product_cost']);
			if (empty($product_cost)) {
				$product_cost = floatval($value['product_cost']);
			}
			
			$special = $value['sale_price'];
			$specialml = $value['sale_price'];

			$product_specials = $this->model_catalog_mvd_product->getProductSpecials($value['product_id']);

			foreach ($product_specials  as $product_special) {
				// var_dump($product_special);
				if ($product_special['customer_group_id']==1) {
					if (($product_special['date_start'] == '0000-00-00' || strtotime($product_special['date_start']) < time()) && ($product_special['date_end'] == '0000-00-00' || strtotime($product_special['date_end']) > time())) {
					
						$special = $product_special['price'];
						if ($product_special['customer_group_id']==1) {
							// if (($product_special['date_start'] == '0000-00-00' || strtotime($product_special['date_start']) < time()) && ($product_special['date_end'] == '0000-00-00' || strtotime($product_special['date_end']) > time())) {
							// 	// echo 11;
								$specialml = $product_special['price'];

								// break;
							// }
						}
					}
				}
				$special2 = 0;
				if ($product_special['customer_group_id']==2) {
					// if (($product_special['date_start'] == '0000-00-00' || strtotime($product_special['date_start']) < time()) && ($product_special['date_end'] == '0000-00-00' || strtotime($product_special['date_end']) > time())) {
					// 	// echo 11;
						$special2 = $product_special['price'];

						// break;
					// }
				}

			}
			// var_dump($special);
			// var_dump($special2);
			// die();
			$save_data[$key]['special'] =$specialml;
			$save_data[$key]['special2'] =$special2;
			$save_data[$key]['profit'] = (floatval(intval(($specialml-$product_cost)/$specialml*10000))/100).'%  '; //累计毛利率
			$save_data[$key]['newGPRTY'] = (floatval(intval(($reportInfo[$value['product_code']]['avgPriceThisYear']-$product_cost)/$reportInfo[$value['product_code']]['avgPriceThisYear']*10000))/100).'%  '; 
			// var_dump($reportInfo[$value['product_code']]['avgPriceThisYear']);
			// var_dump($save_data[$key]['newGPRTY']);
			// var_dump($special);
			// var_dump($product_costn); die();
			$save_data[$key]['profitn'] = (floatval(intval(($specialml-$product_costn)/$specialml*10000))/100).'%  '; //毛利率
			$save_data[$key]['super_profit'] = (floatval(intval(($save_data[$key]['price']-$product_cost)/$save_data[$key]['price']*10000))/100).'%  '; //超市毛利率
		}
		$this->load->library('PHPExcel/PHPExcel');
		$objPHPExcel = new PHPExcel();    
		$objProps = $objPHPExcel->getProperties();    
		$objProps->setCreator("Think-tec");
		$objProps->setLastModifiedBy("Think-tec");    
		$objProps->setTitle("Think-tec Contact");    
		$objProps->setSubject("Think-tec Contact Data");    
		$objProps->setDescription("Think-tec Contact Data");    
		$objProps->setKeywords("Think-tec Contact");    
		$objProps->setCategory("Think-tec");
		$objPHPExcel->setActiveSheetIndex(0);     
		$objActSheet = $objPHPExcel->getActiveSheet(); 
		   
		$objActSheet->setTitle('不带库存');
		$col_idx = 'A';
		$headers = array('编号','供应商编号','供应商名称','品牌','商品唯一码','货架名称','是否是货架商品','品牌','品名','条码','大分类','中分类','小分类','型号','装箱数','中包装','最小起订量','不含税含运费价','百货栈售价','累计毛利率','毛利率','超市建议售价','超市毛利率','引进时间','目前状态','订购数量','订购金额','是否为清仓商品','用户购买量','送货周期','平均进货周期','是否包含在组合商品','备货状态');
		$row_keys = array('product_id','lastname','vendor_name','maname','shelfName','product_code','is_shelf_product','mname','name', 'sku','product_class1','product_class2','product_class3','model','packing_no','middle_package','minimum','product_cost','special','profit','profitn','price','super_profit','date_added','status','BUYQTY','BUYPRICE','clearance','SALEQTY','AVC','optime','isChild','ready');
        foreach ($warehouseList as $warehouseInfo) {
            $headers[] = $warehouseInfo['name'];
            $row_keys[] = 'wh_'.$warehouseInfo['warehouse_id'];
        }
		foreach ($headers as $header) {
			$objActSheet->setCellValue($col_idx++.'1', $header);	
		}
		//添加物流信息
		$i = 2;
		foreach ($save_data as $rlst) {
			$col_idx = 'A';
			foreach ($row_keys as $rk) {
				if($rk == "price" || $rk == "product_cost"){
					$objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_NUMERIC);
					$objActSheet->getDefaultStyle()->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
				}
				else{
					$objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
				}
			}
			$i++;
		}
		
		$sheet2 = new PHPExcel_Worksheet($objPHPExcel, '带库存');
		$objPHPExcel->addSheet($sheet2);
		$objPHPExcel->setActiveSheetIndex(1);
		$objActSheet = $objPHPExcel->getActiveSheet();
		$col_idx = 'A';

		$headers = array('商品ID','商品状态','厂商编号','厂商名称','品牌','分类','大分类','中分类','小分类','商品名称','商品编码','货架名称','是否是货架商品','货号','最小起订量','可卖量（前台库存）','备货状态','可用库存（后台库存）','成本', '目前售价','商品售价','零售参考价','累计毛利率','毛利率','条形码','长','宽','高','重量(kg)','箱入数','最小进货数','排序编号','上架时间','是否单卖（A/B类商品）','上周销量','上周销售额','上四周销量','上四周销售额','年至今销量','年至今销售额','年至今毛利','库存数量','安全库存','库存成本','库存预计销售周期（天）','订购数量','是否为清仓商品','缺货状态','用户购买量','订购金额','在途数量预计销售周期（周）','是否包含在组合商品','2017销售额','2017销量','客户最近一个月退货量','正规标准连锁');
		$row_keys = array('product_id','status','lastname','vendor_name','maname','cd_name','product_class1','product_class2','product_class3','name', 'product_code','shelfName','is_shelf_product','item_no','minimum','quantity','ready','SQN','product_cost','special','sale_price','price','profit','profitn','sku','length','width','height','weight','packing_no','min_purchase_no','sort_order','date_added','is_single','TQLW','TPLW','TQLM','TPLM','TQTY','TPTY','newGPRTY','SQN','SAFE','SCN','SSC','BUYQTY','clearance','Lack_status','SALEQTY','BUYPRICE','SIOWSC','isChild','TP2017','TQ2017','roInfo','special2');

        foreach ($warehouseList as $warehouseInfo) {
            $headers[] = $warehouseInfo['name'];
            $row_keys[] = 'wh_'.$warehouseInfo['warehouse_id'];
        }

		foreach ($headers as $header) {
			$objActSheet->setCellValue($col_idx++.'1', $header);	
		}
		//添加物流信息
		$i = 2;
		foreach ($save_data as $rlst) {
			$col_idx = 'A';
			foreach ($row_keys as $rk) {
				// $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]);	
				$objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
			}
			$i++;
		}

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		ob_end_clean();
		// Redirect output to a client’s web browser (Excel2007)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="Products_'.date('Y-m-d',time()).'.xlsx"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');

		// If you're serving to IE over SSL, then the following may be needed
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0
		 
    $objWriter->save('php://output'); 

    exit;
	}

	public function exportlistsadd(){
		$a =time();

		if (isset($this->request->get['filter_name'])) {
			$filter_name = $this->request->get['filter_name'];
			$filter_data['pd.name'] = array('like','%'.$filter_name.'%');
		} else {
			$filter_name = null;
		}

		if (isset($this->request->get['filter_model'])) {
			$filter_model = $this->request->get['filter_model'];
			$filter_data['p.model'] = array('like','%'.$filter_model.'%');
		} else {
			$filter_model = null;
		}

		if (isset($this->request->get['filter_price'])) {
			$filter_price = $this->request->get['filter_price'];
			$filter_data['p.price'] = $filter_price;
		} else {
			$filter_price = null;
		}

		if (isset($this->request->get['filter_quantity'])) {
			$filter_quantity = $this->request->get['filter_quantity'];
			$filter_data['p.quantity'] = trim($filter_quantity);
		} else {
			$filter_quantity = null;
		}

		if (isset($this->request->get['filter_status'])) {
			$filter_status = $this->request->get['filter_status'];
			$filter_data['p.status'] = $filter_status;
		} else {
			$filter_status = null;
		}
		
		//mvds
		if (isset($this->request->get['filter_sku'])) {
			$filter_sku = $this->request->get['filter_sku'];
			$filter_data['p.sku'] = array('like','%'.$filter_sku.'%');
		} else {
			$filter_sku = null;
		}
		
		//商品编码
		if (isset($this->request->get['filter_product_code'])) {
			$filter_product_code = $this->request->get['filter_product_code'];
			$filter_data['p.product_code'] = array('like','%'.$filter_product_code.'%');
		} else {
			$filter_product_code = null;
		}
			
		if (isset($this->request->get['filter_vendor'])) {
			$filter_vendor = $this->request->get['filter_vendor'];
		} else {
			$filter_vendor = NULL;
		}
			
		if (isset($this->request->get['filter_vendor_name'])) {
			$filter_vendor_name = $this->request->get['filter_vendor_name'];
			$filter_data['vs.vendor_id'] = $filter_vendor_name;
		} else {
			$filter_vendor_name = NULL;
		}
		$this->load->model('catalog/mvd_product');
		$allProduct_data = $this->model_catalog_mvd_product->getAllProductsDetail($filter_data);
		$status_array = array(
			'1' => '启用',
			'0'	=> '停用',
			'5' => '待审批',
			'3' => '初始',
			);

		$this->load->model('stock/stocksearch');
        $this->load->model('stock/warehouse');
        $this->load->model('sale/order');
        $Buyagvpric = $this->model_stock_stocksearch->getAgvBuy();
        $daysale = $this->model_stock_stocksearch->getdaysale();
        // $deliverycycle = $this->model_stock_stocksearch->deliverycycle();
        $poqty= $this->model_stock_stocksearch->getpoqty();
        $BuyNumber = $this->model_stock_stocksearch->getInventorynumber($daysale,$poqty);
        // var_dump($BuyNumber);die();
        foreach ($allProduct_data as $key => $value) {

            if ($value['product_id'] < 1){//屏蔽 product_id=0 的脏数据
                continue;
            }
            $isSingle = (1 == $value['is_single'])? 'A' : 'B' ;
            
			
			/*判断是否存在于组合商品*/
			if($value['product_type'] == 1){
				$temp = $this->model_catalog_mvd_product->checkChild($value['product_id']);
				// $shelfName = $this->model_catalog_mvd_product->getShelf($value['product_id']);
				if (!empty($shelfName)) {
					if ($value['is_shelf_product']==0) {
						M('product')->where(array('product_id'=>$value['product_id']))->save(array('is_shelf_product'=>1));
					}
				}else{
					if ($value['is_shelf_product']==1) {
						M('product')->where(array('product_id'=>$value['product_id']))->save(array('is_shelf_product'=>0));
					}
				}

				//获取平均进货周期
				// $optime = $this->model_catalog_mvd_product->gettime($value['product_code']);

				
				if($temp == 1){
					$isChild = "是";
				}
				else if($temp == 0){
					$isChild = "否";
				}

			}
			else{
				$isChild = "我就是组合";
			}
			/*判断是否存在于组合商品*/
			
			$isStock = 0;
			foreach ($warehouseList as $warehouseInfo) {
                $temp = $inventoryInfo[$value['product_code']][$warehouseInfo['warehouse_id']]['availableQty'];
				if($temp > 0){
					$isStock = 1;
					break;
				}
            }

			/*判断是否备货中*/
			if($value['status'] == 3){
				$ready = "初始";
			}
			else if($value['status'] == 0){
				$ready = "停用";
			}
			else if($value['lack_status'] ==2){
				$ready = "暂时缺货";
			}
			else if($value['lack_status'] == 3){
				$ready = "永久缺货";
			}
			else if($value['clearance'] == 1){
				$ready = "清仓商品";
			}
			else if($value['quantity'] < $value['minimum'] || ($isStock == 0 && $value['product_type'] == 1&&$value['product_class1']!=852)){
				$ready = "备货中";
			}
			else{
				$ready = "有货";
			}
        	// var_dump($roInfo);die();

			$save_data[$key] = array(
				'product_id' 	=> $value['product_id'],	
				'maname' 	=> $value['maname'],	
				'lastname'		=> $value['lastname'],
				'vendor_name'	=> $value['vendor_name'],
				'product_code' => $value['product_code'],
				'mname'			=> $value['mname'],
				'name'          => $value['name'],
				'p_type' => $value['p_type'],
				'sku'			=> $value['sku'],
				'product_class1' =>$value['product_class1'],
				'product_class2' =>$value['product_class2'],
				'product_class3' =>$value['product_class3'],
				'model'			=> $value['model'],
				'packing_no'	=> $value['packing_no'],
				'middle_package'	=> $value['middle_package'],
				'minimum'		=> $value['minimum'],
				'product_cost'	=> $value['product_cost'],
				'price'			=> $value['price'],
				'sale_price'			=> $value['sale_price'],
				'date_added'	=> $value['date_added'],
				'status'		=> $status_array[$value['status']],
				'item_no'		=> $value['item_no'],
				'min_purchase_no'=>$value['min_purchase_no'],
				'quantity'		=> $value['quantity'],
				'length'		=> $value['length'],
				'height'		=> $value['height'],
				'width'			=> $value['width'],
				'weight'		=> $value['weight'],
				'sort_order'	=> $value['sort_order'],
				'ovd_name'      => $value['ovd_name'],
				'cd_name'		=> $value['cd_name'],
                'is_single'     => $isSingle,
                'is_shelf_product'=>$value['is_shelf_product']?'是':'否',
                'BuyNumber'        => $BuyNumber[$value['product_code']]['nums'],
                'safe_quantity'        => $BuyNumber[$value['product_code']]['safe_quantity'],

            );

			            //如果有平均进货价取平均，没有取进货价
			$product_cost = $Buyagvpric[$value['product_code']]['buyav'];
			$product_costn = floatval($value['product_cost']);
			if (empty($product_cost)) {
				$product_cost = floatval($value['product_cost']);
			}
			
			$special = $value['sale_price'];

			$product_specials = $this->model_catalog_mvd_product->getProductSpecials($value['product_id']);

			foreach ($product_specials  as $product_special) {
				if (($product_special['date_start'] == '0000-00-00' || strtotime($product_special['date_start']) < time()) && ($product_special['date_end'] == '0000-00-00' || strtotime($product_special['date_end']) > time())) {
				
					$special = $product_special['price'];

					break;
				}
			}
			$save_data[$key]['special'] =$special;
			$save_data[$key]['profit'] = (floatval(intval(($special-$product_cost)/$special*10000))/100).'%  '; //累计毛利率
			$save_data[$key]['newGPRTY'] = (floatval(intval(($reportInfo[$value['product_code']]['avgPriceThisYear']-$product_cost)/$reportInfo[$value['product_code']]['avgPriceThisYear']*10000))/100).'%  '; 
			// var_dump($reportInfo[$value['product_code']]['avgPriceThisYear']);
			// var_dump($save_data[$key]['newGPRTY']);
			// var_dump($special);
			// var_dump($product_costn); die();
			$save_data[$key]['profitn'] = (floatval(intval(($special-$product_costn)/$special*10000))/100).'%  '; //毛利率
			$save_data[$key]['super_profit'] = (floatval(intval(($save_data[$key]['price']-$product_cost)/$save_data[$key]['price']*10000))/100).'%  '; //超市毛利率
		}
		$this->load->library('PHPExcel/PHPExcel');
		$objPHPExcel = new PHPExcel();    
		$objProps = $objPHPExcel->getProperties();    
		$objProps->setCreator("Think-tec");
		$objProps->setLastModifiedBy("Think-tec");    
		$objProps->setTitle("Think-tec Contact");    
		$objProps->setSubject("Think-tec Contact Data");    
		$objProps->setDescription("Think-tec Contact Data");    
		$objProps->setKeywords("Think-tec Contact");    
		$objProps->setCategory("Think-tec");
		$objPHPExcel->setActiveSheetIndex(0);     
		$objActSheet = $objPHPExcel->getActiveSheet(); 
		   
		$objActSheet->setTitle('不带库存');
		$col_idx = 'A';
		$headers = array('编号','供应商编号','供应商名称','品牌','商品唯一码','是否是货架商品','品牌','品名','条码','大分类','中分类','小分类','型号','装箱数','中包装','最小起订量','不含税含运费价','百货栈售价','累计毛利率','毛利率','超市建议售价','超市毛利率','引进时间','目前状态','建议补货数量','安全库存');
		$row_keys = array('product_id','lastname','vendor_name','maname','product_code','is_shelf_product','mname','name', 'sku','product_class1','product_class2','product_class3','model','packing_no','middle_package','minimum','product_cost','special','profit','profitn','price','super_profit','date_added','status','BuyNumber','safe_quantity');
        foreach ($warehouseList as $warehouseInfo) {
            $headers[] = $warehouseInfo['name'];
            $row_keys[] = 'wh_'.$warehouseInfo['warehouse_id'];
        }
		foreach ($headers as $header) {
			$objActSheet->setCellValue($col_idx++.'1', $header);	
		}
		//添加物流信息
		$i = 2;
		foreach ($save_data as $rlst) {
			$col_idx = 'A';
			foreach ($row_keys as $rk) {
				if($rk == "price" || $rk == "product_cost"){
					$objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_NUMERIC);
					$objActSheet->getDefaultStyle()->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
				}
				else{
					$objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
				}
			}
			$i++;
		}
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		ob_end_clean();
		// Redirect output to a client’s web browser (Excel2007)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="Products_'.date('Y-m-d',time()).'.xlsx"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');

		// If you're serving to IE over SSL, then the following may be needed
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0
		 
    $objWriter->save('php://output'); 

    exit;
	}
	

	public function exportcombin(){
		$a =time();
		$this->load->model('catalog/mvd_product');
		$pardata = $this->model_catalog_mvd_product->getParentdetail();
		$allProduct_data = $this->model_catalog_mvd_product->getAllProductsDetailcombin();
		$status_array = array(
			'1' => '启用',
			'0'	=> '停用',
			'5' => '待审批',
			'3' => '初始',
			);
        $this->load->model('stock/stocksearch');
        $this->load->model('sale/order');
        $reportInfo = $this->model_sale_order->getGatherSaleReport($this->model_stock_stocksearch->getGatherQty());
        $BuyInfo = $this->model_stock_stocksearch->getGatherBuyQtyBy();
        //获取平均进货价
        $Buyagvpric = $this->model_stock_stocksearch->getAgvBuy();
        // var_dump($Buyagvpric);die();
        $BuyInfo = $this->model_stock_stocksearch->getGatherBuyQtyBy();
        $dcycle = $this->model_stock_stocksearch->getDeliveryCycleall();
        $saleqty = $this->model_stock_stocksearch->getAllsaleqty();

		foreach ($allProduct_data as $key => $value) {
			// var_dump($dcycle[$value['product_code']]);
            if ($value['product_id'] < 1){//屏蔽 product_id=0 的脏数据
                continue;
            }
            $keyco = $value['product_code'].$value['parent_product_code'];
            $isSingle = (1 == $value['is_single'])? 'A' : 'B' ;
			$save_data[$key] = array(
                'parname'        => $pardata[$keyco]['parname'],
                'parent_product_code'        => $pardata[$keyco]['parent_product_code'],
                'parquantity'        => $pardata[$keyco]['parquantity'],
                'parproduct_cost'        => $pardata[$keyco]['parproduct_cost'],
                'parprice'        => $pardata[$keyco]['parprice'],
                'child_quantity'        => $value['child_quantity'],
				'product_id' 	=> $value['product_id'],	
				'lastname'		=> $value['lastname'],
				'vendor_name'	=> $value['vendor_name'],
				'product_code' => $value['product_code'],
				'mname'			=> $value['mname'],
				'name'          => $value['name'],
				'p_type' => $value['p_type'],
				'sku'			=> $value['sku'],
				'product_class1' =>$value['product_class1'],
				'product_class2' =>$value['product_class2'],
				'product_class3' =>$value['product_class3'],
				'model'			=> $value['model'],
				'packing_no'	=> $value['packing_no'],
				'middle_package'	=> $value['middle_package'],
				'minimum'		=> $value['minimum'],
				'product_cost'	=> $value['product_cost'],
				'price'			=> $value['price'],
				'date_added'	=> $value['date_added'],
				'status'		=> $status_array[$value['status']],
				'item_no'		=> $value['item_no'],
				'min_purchase_no'=>$value['min_purchase_no'],
				'quantity'		=> $value['quantity'],
				'length'		=> $value['length'],
				'height'		=> $value['height'],
				'width'			=> $value['width'],
				'weight'		=> $value['weight'],
				'sort_order'	=> $value['sort_order'],
				'ovd_name'      => $value['ovd_name'],
				'cd_name'		=> $value['cd_name'],
                'is_single'     => $isSingle,
                'TQLW'          => $reportInfo[$value['product_code']]['TQLW'],
                'TPLW'          => $reportInfo[$value['product_code']]['TPLW'],
                'TQLM'          => $reportInfo[$value['product_code']]['TQLM'],
                'TPLM'          => $reportInfo[$value['product_code']]['TPLM'],
                'TQTY'          => $reportInfo[$value['product_code']]['TQTY'],
                'TPTY'          => $reportInfo[$value['product_code']]['TPTY'],
                'GPRTY'         => $reportInfo[$value['product_code']]['GPRTY'],
                'SQN'           => $reportInfo[$value['product_code']]['SQN'],
                'SCN'           => ($reportInfo[$value['product_code']]['SQN']*$value['product_cost']),
                'SSC'           => $reportInfo[$value['product_code']]['SSC'],
                'SIOW'          => $reportInfo[$value['product_code']]['SIOW'],
                'SIOWSC'        => $reportInfo[$value['product_code']]['SIOWSC'],
                'SAFE'        => $reportInfo[$value['product_code']]['SAFE'],
                'BUYQTY'        => $BuyInfo[$value['product_code']]['buyqty'],
                'BUYPRICE'        => $BuyInfo[$value['product_code']]['buyprice'],
                'AVC'        => $dcycle[$value['product_code']]['av'],
                'SALEQTY'        => $saleqty[$value['product_code']]['quantity'],
                'clearance'     => $value['clearance'],

            );
            //如果有平均进货价取平均，没有取进货价
			$product_cost = $Buyagvpric[$value['product_code']]['buyav'];
			$product_costn = floatval($value['product_cost']);
			if (empty($product_cost)) {
				$product_cost = floatval($value['product_cost']);
			}
			
			$special = $value['sale_price'];
			
			$product_specials = $this->model_catalog_mvd_product->getProductSpecials($value['product_id']);

			foreach ($product_specials  as $product_special) {
				if (($product_special['date_start'] == '0000-00-00' || strtotime($product_special['date_start']) < time()) && ($product_special['date_end'] == '0000-00-00' || strtotime($product_special['date_end']) > time())) {
				
					$special = $product_special['price'];

					break;
				}
			}
			$parspecial = M('product_special')->where('product_id='.$pardata[$keyco]['parent_product_id'])->field('price')->find();
			$save_data[$key]['special'] =$special;
			$save_data[$key]['parspecial'] =$parspecial['price'];
			$save_data[$key]['profit'] = (floatval(intval(($special-$product_cost)/$special*10000))/100).'%  '; //累计毛利率
			//var_dump($special);
			//var_dump($product_costn); die();
			$save_data[$key]['profitn'] = (floatval(intval(($special-$product_costn)/$special*10000))/100).'%  '; //毛利率
			$save_data[$key]['super_profit'] = (floatval(intval(($save_data[$key]['price']-$product_cost)/$save_data[$key]['price']*10000))/100).'%  '; //超市毛利率
		}
		foreach ($save_data as $key => $arr2) {
				$flag[]=$arr2["parent_product_code"];
		}

		array_multisort($flag, SORT_ASC, $save_data);
		$this->load->library('PHPExcel/PHPExcel');
		$objPHPExcel = new PHPExcel();    
		$objProps = $objPHPExcel->getProperties();    
		$objProps->setCreator("Think-tec");
		$objProps->setLastModifiedBy("Think-tec");    
		$objProps->setTitle("Think-tec Contact");    
		$objProps->setSubject("Think-tec Contact Data");    
		$objProps->setDescription("Think-tec Contact Data");    
		$objProps->setKeywords("Think-tec Contact");    
		$objProps->setCategory("Think-tec");
		$objPHPExcel->setActiveSheetIndex(0);     
		$objActSheet = $objPHPExcel->getActiveSheet(); 
		   
		$objActSheet->setTitle('不带库存');
		$col_idx = 'A';
		$headers = array('组合商品名称','组合商品编码','组合商品成本', '组合商品特价','组合商品零售参考价','包含商品数量','编号','供应商编号','供应商名称','商品唯一码','品牌','品名','条码','大分类','中分类','小分类','型号','装箱数','中包装','最小起订量','不含税含运费价','百货栈售价','累计毛利率','毛利率','超市建议售价','超市毛利率','引进时间','目前状态','订购数量','订购金额','是否为清仓商品','用户购买量','送货周期');
		$row_keys = array('parname','parent_product_code','parproduct_cost','parspecial','parprice','child_quantity','product_id','lastname','vendor_name','product_code','mname','name', 'sku','product_class1','product_class2','product_class3','model','packing_no','middle_package','minimum','product_cost','special','profit','profitn','price','super_profit','date_added','status','BUYQTY','BUYPRICE','clearance','SALEQTY','AVC');
		foreach ($headers as $header) {
			$objActSheet->setCellValue($col_idx++.'1', $header);	
		}
		//添加物流信息
		$i = 2;
		foreach ($save_data as $rlst) {
			$col_idx = 'A';
			foreach ($row_keys as $rk) {
				if($rk == "price" || $rk == "product_cost"){
					$objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_NUMERIC);
					$objActSheet->getDefaultStyle()->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
				}
				else{
					$objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
				}
			}
			$i++;
		}

		$sheet2 = new PHPExcel_Worksheet($objPHPExcel, '带库存');
		$objPHPExcel->addSheet($sheet2);
		$objPHPExcel->setActiveSheetIndex(1);
		$objActSheet = $objPHPExcel->getActiveSheet();
		$col_idx = 'A';

		$headers = array('组合商品名称','组合商品编码','组合商品成本', '组合商品特价','组合商品零售参考价','包含商品数量','商品ID','商品状态','厂商编号','厂商名称','分类','大分类','中分类','小分类','商品名称','商品编码','货号','可卖量（前台库存）','可用库存（后台库存）','成本', '售价','零售参考价','累计毛利率','毛利率','条形码','长','宽','高','重量(kg)','箱入数','最小进货数','最小起订量','排序编号','上架时间','是否单卖（A/B类商品）','上周销量','上周销售额','上四周销量','上四周销售额','年至今销量','年至今销售额','年至今毛利','库存数量','安全库存','库存成本','库存预计销售周期（天）','在途订量','订购数量','是否为清仓商品','用户购买量','订购金额','在途数量预计销售周期（周）');
		$row_keys = array('parname','parent_product_code','parproduct_cost','parspecial','parprice','child_quantity','product_id','status','lastname','vendor_name','cd_name','product_class1','product_class2','product_class3','name', 'product_code','item_no','quantity','SQN','product_cost','special','price','profit','profitn','sku','length','width','height','weight','packing_no','min_purchase_no','minimum','sort_order','date_added','is_single','TQLW','TPLW','TQLM','TPLM','TQTY','TPTY','GPRTY','SQN','SAFE','SCN','SSC','SIOW','BUYQTY','clearance','SALEQTY','BUYPRICE','SIOWSC');

		foreach ($headers as $header) {
			$objActSheet->setCellValue($col_idx++.'1', $header);	
		}
		//添加物流信息
		$i = 2;
		foreach ($save_data as $rlst) {
			$col_idx = 'A';
			foreach ($row_keys as $rk) {
				// $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]);	
				$objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
			}
			$i++;
		}

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		ob_end_clean();
		// Redirect output to a client’s web browser (Excel2007)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="Products_'.date('Y-m-d',time()).'.xlsx"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');

		// If you're serving to IE over SSL, then the following may be needed
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0

    $objWriter->save('php://output'); 

    exit;
	}

    /*
     * 维护销售组合时的简单产品筛选功能
     * @author sonicsjh
     * 暂时只支持到product表的product code字段
     */
    public function productSearchForGroup() {
        $this->load->language('catalog/mvd_product');
        $filter['name'] = trim($this->request->get['filter_name']);
        $filter['code'] = trim($this->request->get['filter_code']);
        $filter['sku'] = trim($this->request->get['filter_sku']);
        $filter['thisProduct'] = (int)$this->request->get['this_product'];
        $pageNum = max(1, (int)$this->request->get['page']);

        if ('' == $filter['name'] && '' == $filter['code'] && '' == $filter['sku']){
            $json['success'] = false;
            $json['info'] = $this->language->get('error_filter_empty');
        }else{
            $this->load->model('catalog/mvd_product');
            $this->load->model('tool/image');
            $productList = array();
            $list = $this->model_catalog_mvd_product->productSearchForGroup($filter, $pageNum);
            foreach ($list as $info){
                if (is_file(DIR_IMAGE.$info['image'])) {
                    $image = $this->model_tool_image->resize($info['image'], 40, 40);
                }else{
                    $image = $this->model_tool_image->resize('no_image.png', 40, 40);
                }
                $specialPrice = $this->model_catalog_mvd_product->getSpecialPrice($info['product_id']);
                if ($specialPrice <= 0) {//sp 表无有效特价时，取 p.sale_price 作为零售价
                    $specialPrice = round($info['sale_price'], 2);
                }
                $productList[] = array(
                    'sku' => $info['product_id'].'_'.$info['product_code'],
                    'product_id' => $info['product_id'],
                    'product_code' => $info['product_code'],
                    'product_name' => $info['name'],
                    'image' => $image,
                    'status' => $info['status'],
                    'product_price' => round($info['price'], 2),
                    'product_cost' => round($info['product_cost'],2),
                    'product_special_price' => $specialPrice,
                );
            }
            $json['success'] = true;
            $json['info'] = '';
            $json['data'] = $productList;
        }
        $this->response->addHeader('Content-Type: application/json');
        $this->response->setOutput(json_encode($json));
    }

    protected function _initChildProducts($productList) {
        $this->load->model('tool/image');
        foreach ($productList as $k=>$product){
            if (is_file(DIR_IMAGE.$product['image'])) {
                $productList[$k]['image'] = $this->model_tool_image->resize($product['image'], 40, 40);
            }else{
                $productList[$k]['image'] = $this->model_tool_image->resize('no_image.png', 40, 40);
            }
        }
        return $productList;
    }
	
	//获取二级分类
	public function getClass2(){
		
		$json = array();
		$this->load->model('catalog/mvd_product');
		$parent_id = $this->request->get['parent_id'];

		if($parent_id !="")
		{
			$class2 = $this->model_catalog_mvd_product->getCategoryClass($this->request->get['parent_id']);
		
			foreach($class2 as $value){
			
				$json[] = array(
					'category_id' => $value['category_id'],
					'name' => $value['name'],
					'code' => $value['code']
				);
			}
		}

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));

	}
	
	//自动生成商品编码
	public function createCode(){
		
		$json = array();
		$this->load->model('catalog/mvd_product');

		$classCode = $this->request->get['class_code'];

		$lastcode = $this->model_catalog_mvd_product->searchCode($classCode);
		$newcode =(int)substr($lastcode,-4)+1;
		$tempcode = $newcode/1000;
		$tempcode = str_replace('.','', $tempcode);
		if($tempcode==0){
			$tempcode = '0000';
		}
		else if(strlen($tempcode)==3){
			$tempcode = $tempcode.'0';
		}
		else if(strlen($tempcode)==2){
			$tempcode = $tempcode.'00';
		}
		else if(strlen($tempcode)==1){
			$tempcode = $tempcode.'000';
		}

		$product_code = $classCode.$tempcode;

		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($product_code));

	}

	//上下架
	public function changeStatus(){
		$json['success'] = true;
		if(isset($this->request->get['product_id'])&&isset($this->request->get['op_id'])){
			$product_id = $this->request->get['product_id'];
			$op_id = $this->request->get['op_id'];
			$reason = $this->request->get['reason'];
			$this->load->model('catalog/mvd_product');
			$result = $this->model_catalog_mvd_product->changeStatus($product_id,$op_id);

			/*编辑全文索引*/
			if(strtoupper(substr(PHP_OS, 0, 3)) != 'WIN'){

				$product_info = $this->model_catalog_mvd_product->getProduct($product_id);
				
				$post_data = $product_info;
				$post_data['status'] = $op_id;
				$this->load->model('catalog/xunsearch');
				$this->model_catalog_xunsearch->editDoc($product_id,$post_data);

			}
			/*编辑全文索引*/

			if($result){
				$json['info'] = '设置成功';
				
				$this->load->model('marketing/message');
				$mdata = array(
					'product_id' => $product_id
				);

				//添加历史记录
				switch ($op_id) {
					case '1':
						$comments = '启用(上架)';
						$this->model_catalog_mvd_product->addStHistory($product_id,$this->user->getId(),$comments);
						// $this->model_marketing_message->sendAutoMessage(3,$mdata); //发送上架消息
						break;
					case '0':
						$comments = '停用(下架):'.$reason;
						$this->model_catalog_mvd_product->addStHistory($product_id,$this->user->getId(),$comments);
						// $this->model_marketing_message->sendAutoMessage(2,$mdata); //发送下架消息
						break;
				}
			}else{
			$json['success'] = false;
			$json['info'] = '设置失败';
			}
		}else{
			$json['success'] = false;
			$json['info'] = '设置失败';
		}
		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}

		//上下架通知
	public function notice(){
		$json['success'] = true;
		if(isset($this->request->get['product_id'])&&isset($this->request->get['op_id'])){
			$product_id = $this->request->get['product_id'];
			$op_id = $this->request->get['op_id'];

			$json['info'] = '通知成功';
			
			$this->load->model('marketing/message');
			$mdata = array(
				'product_id' => $product_id
			);

			//添加历史记录
			switch ($op_id) {
				case '3':
					// $comments = '启用(上架)';
					// $this->model_catalog_mvd_product->addStHistory($product_id,$this->user->getId(),$comments);
					$this->model_marketing_message->sendAutoMessage(3,$mdata); //发送上架消息
					break;
				case '2':
					// $comments = '停用(下架):'.$reason;
					// $this->model_catalog_mvd_product->addStHistory($product_id,$this->user->getId(),$comments);
					$this->model_marketing_message->sendAutoMessage(2,$mdata); //发送下架消息
					break;
			}
		}else{
			$json['success'] = false;
			$json['info'] = '设置失败';
		}
		
		$this->response->addHeader('Content-Type: application/json');
		$this->response->setOutput(json_encode($json));
	}


	public function imageexportlists(){
		$a =time();

		if (isset($this->request->get['filter_name'])) {
			$filter_name = $this->request->get['filter_name'];
			$filter_data['pd.name'] = array('like','%'.$filter_name.'%');
		} else {
			$filter_name = null;
		}

		if (isset($this->request->get['filter_model'])) {
			$filter_model = $this->request->get['filter_model'];
			$filter_data['p.model'] = array('like','%'.$filter_model.'%');
		} else {
			$filter_model = null;
		}

		if (isset($this->request->get['filter_price'])) {
			$filter_price = $this->request->get['filter_price'];
			$filter_data['p.price'] = $filter_price;
		} else {
			$filter_price = null;
		}

		if (isset($this->request->get['filter_quantity'])) {
			$filter_quantity = $this->request->get['filter_quantity'];
			$filter_data['p.quantity'] = trim($filter_quantity);
		} else {
			$filter_quantity = null;
		}

		if (isset($this->request->get['filter_status'])) {
			$filter_status = $this->request->get['filter_status'];
			$filter_data['p.status'] = $filter_status;
		} else {
			$filter_status = null;
		}
		
		//mvds
		if (isset($this->request->get['filter_sku'])) {
			$filter_sku = $this->request->get['filter_sku'];
			$filter_data['p.sku'] = array('like','%'.$filter_sku.'%');
		} else {
			$filter_sku = null;
		}
		
		//商品编码
		if (isset($this->request->get['filter_product_code'])) {
			$filter_product_code = $this->request->get['filter_product_code'];
			$filter_data['p.product_code'] = array('like','%'.$filter_product_code.'%');
		} else {
			$filter_product_code = null;
		}
			
		if (isset($this->request->get['filter_vendor'])) {
			$filter_vendor = $this->request->get['filter_vendor'];
		} else {
			$filter_vendor = NULL;
		}
			
		if (isset($this->request->get['filter_vendor_name'])) {
			$filter_vendor_name = $this->request->get['filter_vendor_name'];
			$filter_data['vs.vendor_id'] = $filter_vendor_name;
		} else {
			$filter_vendor_name = NULL;
		}
		$this->load->model('catalog/mvd_product');
		$allProduct_data = $this->model_catalog_mvd_product->getAllProductsDetail($filter_data);
		$status_array = array(
			'1' => '启用',
			'0'	=> '停用',
			'5' => '待审批',
			'3' => '初始',
			);
        $this->load->model('stock/stocksearch');
        $this->load->model('sale/order');
        $reportInfo = $this->model_sale_order->getGatherSaleReport($this->model_stock_stocksearch->getGatherQty());
        $BuyInfo = $this->model_stock_stocksearch->getGatherBuyQtyBy();
        //获取平均进货价
        $Buyagvpric = $this->model_stock_stocksearch->getAgvBuy();
        // var_dump($Buyagvpric);die();
        $BuyInfo = $this->model_stock_stocksearch->getGatherBuyQtyBy();
        $dcycle = $this->model_stock_stocksearch->getDeliveryCycleall();
        $saleqty = $this->model_stock_stocksearch->getAllsaleqty();
        // var_dump($saleqty);

		foreach ($allProduct_data as $key => $value) {
			// var_dump($dcycle[$value['product_code']]);
            if ($value['product_id'] < 1){//屏蔽 product_id=0 的脏数据
                continue;
            }
            $isSingle = (1 == $value['is_single'])? 'A' : 'B' ;
			$save_data[$key] = array(
				'product_id' 	=> $value['product_id'],	
				'maname' 	=> $value['maname'],	
				'lastname'		=> $value['lastname'],
				'vendor_name'	=> $value['vendor_name'],
				'product_code' => $value['product_code'],
				'mname'			=> $value['mname'],
				'name'          => $value['name'],
				'image'          => $value['image'],
				'p_type' => $value['p_type'],
				'sku'			=> $value['sku'],
				'product_class1' =>$value['product_class1'],
				'product_class2' =>$value['product_class2'],
				'product_class3' =>$value['product_class3'],
				'model'			=> $value['model'],
				'packing_no'	=> $value['packing_no'],
				'middle_package'	=> $value['middle_package'],
				'minimum'		=> $value['minimum'],
				'product_cost'	=> $value['product_cost'],
				'price'			=> $value['price'],
				'sale_price'			=> $value['sale_price'],
				'date_added'	=> $value['date_added'],
				'status'		=> $status_array[$value['status']],
				'item_no'		=> $value['item_no'],
				'min_purchase_no'=>$value['min_purchase_no'],
				'quantity'		=> $value['quantity'],
				'length'		=> $value['length'],
				'height'		=> $value['height'],
				'width'			=> $value['width'],
				'weight'		=> $value['weight'],
				'sort_order'	=> $value['sort_order'],
				'ovd_name'      => $value['ovd_name'],
				'cd_name'		=> $value['cd_name'],
                'is_single'     => $isSingle,
                'TQLW'          => $reportInfo[$value['product_code']]['TQLW'],
                'TPLW'          => $reportInfo[$value['product_code']]['TPLW'],
                'TQLM'          => $reportInfo[$value['product_code']]['TQLM'],
                'TPLM'          => $reportInfo[$value['product_code']]['TPLM'],
                'TQTY'          => $reportInfo[$value['product_code']]['TQTY'],
                'TPTY'          => $reportInfo[$value['product_code']]['TPTY'],
                'GPRTY'         => $reportInfo[$value['product_code']]['GPRTY'],
                'SQN'           => $reportInfo[$value['product_code']]['SQN'],
                'SCN'           => ($reportInfo[$value['product_code']]['SQN']*$value['product_cost']),
                'SSC'           => $reportInfo[$value['product_code']]['SSC'],
                'SIOW'          => $reportInfo[$value['product_code']]['SIOW'],
                'SIOWSC'        => $reportInfo[$value['product_code']]['SIOWSC'],
                'SAFE'        => $reportInfo[$value['product_code']]['SAFE'],
                'BUYQTY'        => $BuyInfo[$value['product_code']]['buyqty'],
                'BUYPRICE'        => $BuyInfo[$value['product_code']]['buyprice'],
                'AVC'        => $dcycle[$value['product_code']]['av'],
                'SALEQTY'        => $saleqty[$value['product_code']]['quantity'],
                'clearance'     => $value['clearance'],

            );
            //如果有平均进货价取平均，没有取进货价
			$product_cost = $Buyagvpric[$value['product_code']]['buyav'];
			$product_costn = floatval($value['product_cost']);
			if (empty($product_cost)) {
				$product_cost = floatval($value['product_cost']);
			}
			
			$special = $value['sale_price'];

			$product_specials = $this->model_catalog_mvd_product->getProductSpecials($value['product_id']);

			foreach ($product_specials  as $product_special) {
				if (($product_special['date_start'] == '0000-00-00' || strtotime($product_special['date_start']) < time()) && ($product_special['date_end'] == '0000-00-00' || strtotime($product_special['date_end']) > time())) {
				
					$special = $product_special['price'];

					break;
				}
			}
			$save_data[$key]['special'] =$special;
			$save_data[$key]['profit'] = (floatval(intval(($special-$product_cost)/$special*10000))/100).'%  '; //累计毛利率
			// var_dump($special);
			// var_dump($product_costn); die();
			$save_data[$key]['profitn'] = (floatval(intval(($special-$product_costn)/$special*10000))/100).'%  '; //毛利率
			$save_data[$key]['super_profit'] = (floatval(intval(($save_data[$key]['price']-$product_cost)/$save_data[$key]['price']*10000))/100).'%  '; //超市毛利率
		}

		      //   import("Org.Util.PHPExcel");
        // import("Org.Util.PHPExcel.Worksheet.Drawing");
        // import("Org.Util.PHPExcel.Writer.Excel2007");
		$this->load->library('PHPExcel/PHPExcel');
		$this->load->library('PHPExcel/PHPExcel/Worksheet/Drawing');
        // var_dump($objDrawing);die();
		$objPHPExcel = new PHPExcel();    
		$objProps = $objPHPExcel->getProperties();    
		$objProps->setCreator("Think-tec");
		$objProps->setLastModifiedBy("Think-tec");    
		$objProps->setTitle("Think-tec Contact");    
		$objProps->setSubject("Think-tec Contact Data");    
		$objProps->setDescription("Think-tec Contact Data");    
		$objProps->setKeywords("Think-tec Contact");    
		$objProps->setCategory("Think-tec");
		$objPHPExcel->setActiveSheetIndex(0);     
		$objActSheet = $objPHPExcel->getActiveSheet(); 
		
		$sheet2 = new PHPExcel_Worksheet($objPHPExcel, '带库存');
		$objPHPExcel->addSheet($sheet2);
		$objPHPExcel->setActiveSheetIndex(1);
		$objActSheet = $objPHPExcel->getActiveSheet();
		$col_idx = 'A';

		$headers = array('商品图片','商品ID','商品状态','厂商编号','厂商名称','品牌','分类','大分类','中分类','小分类','商品名称','商品编码','货号','可卖量（前台库存）','可用库存（后台库存）','成本', '目前售价','商品售价','零售参考价','累计毛利率','毛利率','条形码','长','宽','高','重量(kg)','箱入数','最小进货数','最小起订量','排序编号','上架时间','是否单卖（A/B类商品）','上周销量','上周销售额','上四周销量','上四周销售额','年至今销量','年至今销售额','年至今毛利','库存数量','安全库存','库存成本','库存预计销售周期（天）','在途订量','订购数量','是否为清仓商品','用户购买量','订购金额','在途数量预计销售周期（周）');
		$row_keys = array('product_id','status','lastname','vendor_name','maname','cd_name','product_class1','product_class2','product_class3','name', 'product_code','item_no','quantity','SQN','product_cost','special','sale_price','price','profit','profitn','sku','length','width','height','weight','packing_no','min_purchase_no','minimum','sort_order','date_added','is_single','TQLW','TPLW','TQLM','TPLM','TQTY','TPTY','GPRTY','SQN','SAFE','SCN','SSC','SIOW','BUYQTY','clearance','SALEQTY','BUYPRICE','SIOWSC');

		foreach ($headers as $header) {
			$objActSheet->setCellValue($col_idx++.'1', $header);
			// $objPHPExcel->getActiveSheet()->getColumnDimension($col_idx)->setHeight(80);	

		}

		$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(15);	

        // $objActSheet

		//添加物流信息
		$i = 2;
		// var_dump($save_data);
		foreach ($save_data as $rlst) {
			$url='http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"]; 
			// echo dirname($url);
			$objDrawing[$i] = new \PHPExcel_Worksheet_Drawing();
			// var_dump($objDrawing[$i]);
			$image = $rlst['image'];
			$dir = dirname($image);
			$extension = pathinfo($image, PATHINFO_EXTENSION);
			$url = '/usr/share/nginx/html/bhz/image/cache/'.$dir.'/'.$rlst['product_code'].'.'.$extension;
			// if (file_exists($url)) {
			// 	$objDrawing[$i]->setPath($url,1);
	  //           // 设置宽度高度
	  //           $objDrawing[$i]->setHeight(80);//照片高度
	  //           $objDrawing[$i]->setWidth(80); //照片宽度
	  //           /*设置图片要插入的单元格*/
	  //           $objDrawing[$i]->setCoordinates('A'.$i);
	  //           // 图片偏移距离
	  //           $objDrawing[$i]->setOffsetX(0);
	  //           $objDrawing[$i]->setOffsetY(0);
	  //           $objDrawing[$i]->setWorksheet($objPHPExcel->getActiveSheet());
			// }
			// var_dump($url);
			// $url  = iconv('utf-8', 'gb2312', $url);
			// var_dump($url);die();
			if (file_exists($url)) {
				$objDrawing[$i]->setPath($url,1);
	            // 设置宽度高度
	            $objDrawing[$i]->setHeight(80);//照片高度
	            $objDrawing[$i]->setWidth(80); //照片宽度
	            /*设置图片要插入的单元格*/
	            $objDrawing[$i]->setCoordinates('A'.$i);
	            // 图片偏移距离
	            $objDrawing[$i]->setOffsetX(0);
	            $objDrawing[$i]->setOffsetY(0);
	            $objDrawing[$i]->setWorksheet($objPHPExcel->getActiveSheet());
			}
            

			$col_idx = 'B';
			foreach ($row_keys as $rk) {
				// $objActSheet->setCellValue($col_idx++.$i, $rlst[$rk]);	
				$objActSheet->setCellValueExplicit($col_idx++.$i, $rlst[$rk], PHPExcel_Cell_DataType::TYPE_STRING);
			}

			$objActSheet->getRowDimension($i)->setRowHeight(80);
			$i++;
		}

		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		ob_end_clean();
		// Redirect output to a client’s web browser (Excel2007)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="Products_'.date('Y-m-d',time()).'.xlsx"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');

		// If you're serving to IE over SSL, then the following may be needed
		header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
		header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header ('Pragma: public'); // HTTP/1.0
		 
    $objWriter->save('php://output'); 

    exit;
	}

}
